어플리케이션을 개발하기 위해 기본 뼈대가 제공
개발자는 주어진 뼈대에 (business logic)을 붙이는 작업만 수행
아래 예제에서 스프링 컨테이너는 AccountDao를 Bean 객체로 설정하고 각 클래스마다 해당 객체가 필요할 시점에 할당(주입)을 해준다 , 주입을 해주는 방식은 xml방식과 java클래스 방식이 있고 dao객체가 생성되는 방식은 생성자 방식과 Setter 방식이있다
<bean id = "dao" class = "bank.AccountDAO"></bean>
<bean id = "cservice" class = "bank.AccountCreateService">
<constructor-arg ref = "dao"></constructor-arg>
</bean>
<bean id = "tservice" class = "bank.TransactionService">
<constructor-arg ref = "dao"></constructor-arg>
</bean>
우선 dao라는 id를 가진 bean 객체를 생성해주고 class 부분에는 bank라는 패킥지안에 AccountDAO 클래스를 통해 생성을 한 모습이다
다음 아래를 보면 cservice와 tservice라는 이름을 가진 bean 객체가 dao를
생성자 방식으로 생성
할때 constructor-arg 태그를 이용하여 ref안에 bean 객체를 넣어서 생성한다
위 방식이 xml 방식이다
Setter 방식으로 사용하는경우
<bean id = "tv2" class = "di.ex02.LgTV">
<property name = "speaker" ref = "apple"/>
<property name = "model" value = "75인치"/>
</bean>
propery 태그를 이용하여 Setter방식으로 설정한다
//xml파일을 설정 정보로 사용할경우 GenericXmlApplicationContext 클래스 필요
ApplicationContext ctx = new GenericXmlApplicationContext("classpath:config.xml");
@Bean
public AccountDAO dao()
{
return new AccountDAO();
}
@Bean
public BasicReport basicReport()
{
return new BasicReport();
}
//
// @Bean
// public summeryReport sReport()
// {
// return new summeryReport();
// }
//
@Bean(name = "cservice")
public AccountCreateService accountCreateService()
{
return new AccountCreateService(dao());
}
//
@Bean (name = "tservice")
public TransactionService transactionService()
{
return new TransactionService(dao());
}
@Bean (name = "one")
public ReportOneAccountService reportOneAccountService()
{
ReportOneAccountService oneAccountService = new ReportOneAccountService();
oneAccountService.setDao(dao());
oneAccountService.setPrinter(basicReport());
return oneAccountService;
}
@Bean(name = "every")
public ReportEveryAccountService reportEveryAccountService()
{
ReportEveryAccountService oneAccountService = new ReportEveryAccountService();
oneAccountService.setDao(dao());
oneAccountService.setPrinter(basicReport());
return oneAccountService;
}
자바 코드 방식으로 bean 객체를 만드는 방법이고 이 방법을 쓰려면 본 클래스에 @Configuration 어노테이션이 필요하다 이는 클래스를 Bean 설정으로 사용한다는 의미이다
자바를 이용할경우 ApplicationContext는 아래와 같다
ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
<context:annotation-config/> 태그를 입력한다
@Autowired 어노 테이션은 bean객체중에 타입이 하나만있을때 자동으로 연결을 해주는 것으로 코드가 간결해진다 @Autowired 어노테이션은 생성자와 필드 메서드 총 세 곳에 적용가능하다
@Qualifier : 같은 타입의 객체가 여러개가 있을경우 연결할 객체를 한정할 때 사용
@Resource : 위 두개의 어노테이션을 합친것 이름을 기준으로 선택 @Autowired는 타입을 기준으로 선택
@Inject : @Autowired 와 같은 의미
XML을 통한 DI 설정시 <context:annotation-config/> 내용이 포함 되어 있어야 한다
Bean으로 등록할 클래스에 @Component annotation을 추가 같은 타입일 경우 @Component("bean"아이디)를 이용