티스토리 뷰

Backend/Spring

Spring. Bean 생성과 사용

out of coding 2020. 1. 19. 12:12

아마도 Bean에 대해서는 많이 봤을 겁니다.

싫던 좋던 XML의 beans아래에 bean을 넣어서 사용하기도 하였고요.

@Configuration에 넣어서 사용하기도 하였죠.

 

두개의 Component가 있다고 하겠습니다.

@Component
public class People {

    private Country country;

    @Autowired
    public People(Country country) {
        this.country = country;
    }
    
    public String getCountryName() {
        return country.name();
    }

    public void printCountry() {
        country.printText();
    }
}
@Component("country")
public class Country {

    public String name() {
        return "Korea";
    }

    public void printText() {
        System.out.println("Country is " + name());
    }
}

People은 Country가 필요하겠죠?

예제를 드럽게 못 만들었네요 ㅎㅎㅎ 

 

XML을 이용

applicationContext.xml 파일에 다음처럼 추가하여서 사용이 가능합니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	<bean id="country" class="com.example.Country"></bean>
	<bean id="people" class="com.example.People">
		<property name="country" ref="country"></property>
	</bean>
</beans>

이건 코드에서 다음과 같이 사용이 가능합니다.

public void some() {
	ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		
	People people = (People)context.getBean("country");
	System.out.println(people.getCountryName());
}

잘보면 People에 Country를 넣어주는 행동을 xml에서 했지만 다른걸 넣어주지는 않았습니다.

 

Annotation을 이용

ApplicationConfig.java가 있지만 서로 다르게 Config들을 관리 할 수 있는것을 보여드리기 위해서 파일을 하나 더 추가하였습니다.

@Configuration
@ComponentScan("com.example")
public class PeopleConfig {

}

다음과 같이 사용하면 됩니다.

public void some() {
	ApplicationContext context = new AnnotationConfigApplicationContext(BookConfig.class);
	People people = context.getBean(People.class);
	System.out.println(people.getCountryName());
}

 

저는 개인적으로 XML은 별로네요.

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함