빈을 등록하다보면 constructor-arg를 쓸때가 있다
어떨때 property를 사용하고 어떨때 constructor-arg를 사용하는지 알아보자.
Setter Injection:<property>태그
Setter메소드를 통해 의존 관계가 있는 Bean을 주입하려면 <property>태그를 사용할수있다.
- ref 속성을 사용하면 Bean 이름을 이용해 주입할 Bean을 찾는다.
- value 속성은 단순 값 또는 Bean이 아닌 객체를 주입할 때 사용한다.
Constructor Injection : <constructor-arg>태그
Constructor를 통해 의존 관계가 있는 Bean을 주입하려면 <constructor-arg>태그를 사용 할 수 있다.
Constructor 주입 방식은 생성자의 파라미터를 이용하기 때문에 한번에 여러개의 객체를 주입할 수 있다.
- index 속성을 사용하는 방법과 name속성을 이용하는 방법으로 나뉜다.
ex)
private JdbcTemplate jdbcTemplate;
public memberDao(DataSource ds){
this.jdbcTemplate = new JdbcTemplate(ds);
}
<bean id="memberDao" class="spring04_chap11.memberDao>
<constructor-arg ref="dataSource" /></bean>
이런식으로 memberDao클래스 안의 생성자의 인자값으로 dataSource를 의존시켜라라는 뜻으로 빈으로 등록한것이다.
'스프링강의' 카테고리의 다른 글
빈이 두개일때 매칭하는 방법 (0) | 2021.06.21 |
---|---|
LOMBOK(롬복) @RequiredArgsConstructor (0) | 2021.06.21 |
No qualifying bean of type 'hello.core.member.MemberService' available 에러난 이유 (0) | 2021.06.17 |
@Autowired (0) | 2021.06.17 |
BeanFactory, ApplicationContext (0) | 2021.06.12 |