Spring中装配bean的三种主要方式

来源:互联网 发布:富途网络 怎么样 编辑:程序博客网 时间:2024/05/03 08:25

1.自动化配置

package com.springinaction.test;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration//告诉spring这是一个配置类@ComponentScan//扫描组件public class CDPlayerConfig {}
package com.springinaction.test;import org.springframework.stereotype.Component;@Componentpublic class SgtPeppers implements CompactDisc{//CompactDisc是一个接口private String title = "Sgt. Pepper's Linel Hearts Cloub Band";private String artist = "The Beatles";@Overridepublic void play() {System.out.println("Playing " + title + " by " + artist);}}


2.基于java的显示配置:要在java中声明bean,我们需要一个方法

package com.springinaction.test;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class CDPlayerConfig {@Bean//@Bean会告诉Spring这个方法将返回一个对象,该对象要注册为Spring应用上下文中的beanpublic CompactDisc sgtPeppers(){return new SgtPeppers();}}
package com.springinaction.test;import org.springframework.stereotype.Component;//这里没有哦public class SgtPeppers implements CompactDisc{private String title = "Sgt. Pepper's Linel Hearts Cloub Band";private String artist = "The Beatles";@Overridepublic void play() {System.out.println("Playing " + title + " by " + artist);}}

3.基于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"xmlns:Context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"    ><!-- 简单bean引用--><bean id="compactDisc" class="com.springinaction.test.CompactDisc"/><bean id="cdPlayer" class="com.springinaction.test.CdPlayer">        <!-- 构造器中参数为CompactDisc对象 -->        <constructor-arg ref="compactDisc"/>    </bean></beans>
不管采用扫描方式,这些技术都描述了Spring应用中的组件以及这些组件之间的关系;

建议尽可能的使用自动化配置,以避免显示配置带来的维护成本;

如果你确实需要显示配置Spring的话,应该优先选择基于Java的配置,它比基于XML的配置更强大、类型安全并且易于重构!

0 0