개발합니다
[Spring] 어노테이션을 통한 스프링 설정 (Annotation Config) 본문
.xml 파일에 생성한 빈(Bean) 객체들을 @Configration 어노테이션을 사용해서 자바로 작성 가능하다.
1. 기본
@Configuration
public class MemberConfig {
// <bean id="studentDao" class="ems.member.dao.StudentDao" />
@Bean
public StudentDao studentDao() {
return new StudentDao();
}
}
2. <constructor-arg> 태그 사용
/*
* <bean id="registerService" class="ems.member.service.StudentRegisterService">
* <constructor-arg ref="studentDao" ></constructor-arg>
* </bean>
*/
@Bean
public StudentRegisterService registerService() {
return new StudentRegisterService(studentDao());
}
3. setter를 이용한 의존 객체 주입
/*
* <bean id="dataBaseConnectionInfoDev" class="ems.member.DataBaseConnectionInfo">
* <property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:xe" />
* <property name="userId" value="scott" />
* <property name="userPw" value="tiger" />
* </bean>
*/
@Bean
public DataBaseConnectionInfo dataBaseConnectionInfoDev() {
DataBaseConnectionInfo infoDev = new DataBaseConnectionInfo();
infoDev.setJdbcUrl("jdbc:oracle:thin:@localhost:1521:xe");
infoDev.setUserId("scott");
infoDev.setUserPw("tiger");
return infoDev;
}
4. List 타입 객체
/* <property name="developers">
* <list>
* <value>Cheney.</value>
* <value>Eloy.</value>
* <value>Jasper.</value>
* <value>Dillon.</value>
* <value>Kian.</value>
* </list>
* </property>
*/
ArrayList<String> developers = new ArrayList<String>();
developers.add("Cheney.");
developers.add("Eloy.");
developers.add("Jasper.");
developers.add("Dillon.");
developers.add("Kian.");
info.setDevelopers(developers);
5. Map 타입 객체
/* <property name="administrators">
* <map>
* <entry>
* <key>
* <value>Cheney</value>
* </key>
* <value>cheney@springPjt.org</value>
* </entry>
* <entry>
* <key>
* <value>Jasper</value>
* </key>
* <value>jasper@springPjt.org</value>
* </entry>
* </map>
* </property>
*/
Map<String, String> administrators = new HashMap<String, String>();
administrators.put("Cheney", "cheney@springPjt.org");
administrators.put("Jasper", "jasper@springPjt.org");
info.setAdministrators(administrators);
- 메인 클래스에서 접근
// GenericXmlApplicationContext ctx =
// new GenericXmlApplicationContext("classpath:applicationContext.xml");
// 어노테이션을 이용한 스프링 설정
AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(MemberConfig.class);
- 기능 별로 구분한 MemberConfig 파일 @Import
@Configuration
@Import({ MemberConfig2.class, MemberConfig3.class })
public class MemberConfig1 {
.
.
.
}
//@Import를 통해 하나로 통합한 MemberConfig1만 사용
AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(MemberConfig1.class);
'Web > Spring' 카테고리의 다른 글
[Spring] @ModelAttribute , Model & ModelAndView 객체 (0) | 2022.03.25 |
---|---|
[Spring] @RequestMapping , 요청 파라미터 (0) | 2022.03.25 |
[Spring] 의존 객체 자동 주입 (@Autowired, @Resource, @Qualifier, @Inject) (0) | 2022.03.24 |
[Spring] DI(Dependency Injection) - 의존 객체 주입 (0) | 2022.03.24 |
[Spring] Maven 스프링 프로젝트 구조 (0) | 2022.03.24 |