2017. 6. 22.

[Spring] @Component vs @Bean

@Bean

: It is used to indicate that a method instantiates, configures and initializes a new object to be managed by the Spring IOC container. (<beans/> element in Spring XML configuration)


@Component

: Generic stereotype annotation for any Spring-managed component. (<context:component-scan> in Spring XML configuration)

They are most often used with @Configuration annotation. Like this :

@Configuration 
public class AppConfig { 
 @Bean 
   public MyService myService() { 
     return new MyServiceImpl();
   }
}

@Configuration

: Annotating a class with @Configuration indicates that its primary purpose is as a source of bean definitions. Furthermore, @Configuration classes allow inter-bean dependencies to be defined by simply calling other @Bean methods in the same class.


이때 There are following differences between @Component and @Bean.

The @Bean methods in a regular Spring component are processed differently than their counterparts inside a Spring @Configuration class. The difference is that @Component classes are not enhanced with CGLIB to intercept the invocation of methods and fields.

CGLIB proxying is the means by which invoking methods or fields within @Bean methods in @Configuration classes creates bean metadata references to collaborating objects; such methods are not invoked with normal Java semantics but rather go through the container in order to provide the usual lifecycle management and proxying of Spring beans even when referring to other beans via programmatic calls to @Bean methods.

In contrast, invoking a method or field in an @Bean method within a plain @Component class has standard Java semantics, with no special CGLIB processing or other constraints applying.

Plus, @Bean is used for spring library which cannot be control by developer, but we can indicates and controls methods in specific library with @Component annotation.
Like this :


@Component
public class SessionEventHandler implements ApplicationListener<SessionDestroyedEvent> {
    @Autowired
    @Qualifier("sessionRegistry")
    private RedisSessionRegistry sessionRegistry;
    
    @Override
    public void onApplicationEvent(SessionDestroyedEvent event) {
        //Detecting session constantly by login, logout, and the end of redis timeout
        String sessionId = event.getSession().getId();
        SessionInformation sessionInformation = sessionRegistry.getSessionInformation(sessionId);
        
        if (sessionInformation != null) {
            // Clear session completely if sessionInfo is not null
            for (SessionInformation row : sessionRegistry.getAllSessions(sessionInformation.getPrincipal(), true)) {
                row.expireNow();
            }
        }
    }
    
}
cs



    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }
cs

댓글 없음:

댓글 쓰기