예시 코드:
public class GreetingService {
public String greet(String name) {
return "Hello, " + name;
}
}
IoC (Inversion of Control)
개념:
객체 생성과 의존성 관리를 개발자가 아닌 Spring Container가 대신함.
즉, 제어의 주도권이 개발자 → 스프링으로 역전(Inversion) 됨.
DI (Dependency Injection)
개념:
IoC의 구현 방법 중 하나. 필요한 객체를 직접 생성하지 않고 외부에서 주입받는 방식.
예시 코드:
public interface GreetingService {
String greet(String name);
}
@Component
public class GreetingServiceImpl implements GreetingService {
public String greet(String name) {
return "Hello, " + name;
}
}
@Component
public class MyApp {
private final GreetingService greetingService;
// 생성자 주입 방식 (권장)
@Autowired
public MyApp(GreetingService greetingService) {
this.greetingService = greetingService;
}
public void run() {
System.out.println(greetingService.greet("Spring"));
}
}
Spring Boot 실행 예시:
@SpringBootApplication
public class App {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(App.class, args);
MyApp app = context.getBean(MyApp.class);
app.run();
}
}
예시 코드:
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("메서드 호출 전: " + joinPoint.getSignature().getName());
}
@After("execution(* com.example.service.*.*(..))")
public void logAfter(JoinPoint joinPoint) {
System.out.println("메서드 호출 후: " + joinPoint.getSignature().getName());
}
}
예시 코드 (JDBC PSA):
@Repository
public class UserRepository {
private final JdbcTemplate jdbcTemplate;
@Autowired
public UserRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<User> findAll() {
return jdbcTemplate.query("SELECT * FROM users",
(rs, rowNum) -> new User(rs.getLong("id"), rs.getString("name")));
}
}