728x90
반응형
생성자를 생성한후 객체를 생성할 때 마다 새로운 객체가 생성되는것을 막기 위하여
싱글톤 패턴 디자인을 사용하곤 한다, 하지만 이러한 싱글톤 패턴은 많은 양의 코드 추가로 인하여,
코드가 더러워 보이거나 가독성이 떨어지곤 한다. 이러한 단점을 해결하기 위해 SpringBean을 사용한다.
SpringBean을 사용하게 되면, 쓸때없는 코드를 추가하지 않고도 싱글톤을 사용할 수 있다.
SpringBean을 사용할때와 사용하지 않았을 경우를 비교하기 위하여 간단한 예제 코드를 작성하였다.
#testConfig
@Configuration
public class testConfig {
@Bean
public testService testservice(){
return new testService();
}
}
1,SpringBean을 사용하지 않았을 경우
public class testSingletonTest {
@Test
void 싱글톤테스트(){
testConfig testConfig = new testConfig();
testService testService1 = testConfig.testservice();
testService testService2 = testConfig.testservice();
System.out.println("testService1 = " + testService1);
System.out.println("testService2 = " + testService2);
}
}
# SpringBean을 사용하지 않고, testConfig를 직접 생성하여 호출 하였을때이다. 결과로는 ,
위에 이미지 처럼 각각의 객체가 서로 다른것을 확인할 수 있다.
1,SpringBean을 사용했을경우
public class testSingletonTest {
@Test
void 싱글톤테스트(){
ApplicationContext ac = new AnnotationConfigApplicationContext(testConfig.class);
testService testService1 = ac.getBean("testservice" , testService.class);
testService testService2 = ac.getBean("testservice" , testService.class);
System.out.println("testService1 = " + testService1);
System.out.println("testService2 = " + testService2);
}
}
#SpringBean을 사용하여 호출하였을때 결과로는 ,
위에 이미지 처럼 같은 객체임을 알수있다.
728x90
반응형
'개발일기 > Spring' 카테고리의 다른 글
[Spring]@ComponentScan , @Component , @Autowired (0) | 2024.03.18 |
---|---|
[Spring]싱클톤 사용시 주의사항. (0) | 2024.03.18 |
[Spring]BeanFactory , ApplicationContext (0) | 2024.03.18 |
[Spring] ApplicationContext (0) | 2024.03.15 |
IoC(제어의 역전)와 DI(의존성 주입) (0) | 2024.03.15 |