您的位置:首页 > 编程语言 > Java开发

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

2016-05-06 19:12 801 查看
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;

@Component
public class SgtPeppers implements CompactDisc{//CompactDisc是一个接口

private String title = "Sgt. Pepper's Linel Hearts Cloub Band";
private String artist = "The Beatles";

@Override
public 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;

@Configuration
public class CDPlayerConfig {

@Bean//@Bean会告诉Spring这个方法将返回一个对象,该对象要注册为Spring应用上下文中的bean
public 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";

@Override
public 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的配置更强大、类型安全并且易于重构!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: