使用@Configuration注解來代替Spring的bean配置


下面是一個典型的Spring配置文件(application-config.xml):

<beans>  
        <bean id="orderService" class="com.acme.OrderService"/>  
                <constructor-arg ref="orderRepository"/>  
        </bean>  
        <bean id="orderRepository" class="com.acme.OrderRepository"/>  
                <constructor-arg ref="dataSource"/>  
        </bean>  
</beans>  

  然后你就可以像這樣來使用是bean了:

ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml");  
OrderService orderService = (OrderService) ctx.getBean("orderService");  

  現在Spring Java Configuration這個項目提供了一種通過java代碼來裝配bean的方案:

@Configuration  
public class ApplicationConfig {  
  
        public @Bean OrderService orderService() {  
                return new OrderService(orderRepository());  
        }  
  
        public @Bean OrderRepository orderRepository() {  
                return new OrderRepository(dataSource());  
        }  
  
        public @Bean DataSource dataSource() {  
                // instantiate and return an new DataSource …  
        }  
}  

  然后你就可以像這樣來使用是bean了:

JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ApplicationConfig.class);  
OrderService orderService = ctx.getBean(OrderService.class);

  

 這么做有什么好處呢?

     1.使用純java代碼,不在需要xml

     2.在配置中也可享受OO帶來的好處

     3.類型安全對重構也能提供良好的支持

     4.依舊能享受到所有springIoC容器提供的功能


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM