标签:注入 version example his get font 直接 www. list
本文系作者原创,转载请注明出处:http://www.cnblogs.com/further-further-further/p/7717331.html
通过component-scan自动扫描将业务逻辑bean注册到spring容器中,去除XML配置文件bean手动注册过程,降低XML配置文件繁琐性;
1、注册扫描bean并使用@Autowired注解自动装配时,需在XML配置文件中引入 <context:component-scan base-package="com.spring.example.scan"/>;
2、 通过component-scan自动扫描定义基类包下所有bean,需要在类名前加入注解@Component,并且可以自定义bean的id<@Component("instru")>,如果没有定义bean的id就默认类名(全部小写),将扫描的bean装入spring容器;
3、 在spring容器启动后(获取到spring容器的实例),通过Autowired注解以及bean的id(Qualifier)来装配和注入相应的实例对象;
4、 调用实例方法;
spring配置文件component-scan.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/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--自动扫描检测bean以及定义bean,并将bean放入spring容器--> <context:component-scan base-package="com.spring.example.scan"/> </beans>
Instrument接口代码
public interface Instrument { void play(); }
Guitar实现接口Instrument代码
@Component public class Guitar implements Instrument { @Override public void play() { System.out.println("Guitar...."); } }
Performer接口代码
public interface Performer { void perform(); }
Instrumentalist实现接口Performer代码
@Component("instru") //指定bean id public class Instrumentalist implements Performer { public Instrumentalist(){} @Value("Yesterday Once more !") private String song; // @Autowired 可以装配属性、方法、构造函数,只要类型相同(这里是Instrument类型) // 限定歧义性的依赖,使用@Autowired注解自动装配,满足装配的多个bean, // 可以通过@Qualifier指定来缩小范围 @Autowired @Qualifier("guitar") //通过id指定bean private Instrument instrument; public void setSong(String song) { this.song = song; } public void setInstrument(Instrument instrument){ this.instrument = instrument ; } @Override public void perform() { System.out.println("Playing "+ song + " : "); instrument.play(); } }
测试代码
public class Driver extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { try { ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/component-scan.xml"); Performer performer = (Performer) ctx.getBean("instru"); performer.perform(); }catch (Exception e){ e.printStackTrace(); } } }
运行结果
总结
component-scan自动扫描优缺点:
优点: a> component-scan自动扫描注册装配可以有效解决annotation-config的不足,不需要在spring配置文件中需提前指明bean,使配置文件非常简洁;
b> 去除在XML定义bean的过程,在应用程序中直接装配和注入,减少更改类名实导致的错误;
缺点: 不能自动获取第三方接口实例bean;
适用于自身业务逻辑开发;
本文描述可能有不对或不全之处,欢迎大家吐槽!
spring框架应用系列二:component-scan自动扫描注册装配
标签:注入 version example his get font 直接 www. list
原文地址:http://www.cnblogs.com/further-further-further/p/7717331.html