1.在XML中显式配置java
2.在Java中进行显式配置spring
3.隐士的bean发现机制和自动装配ide
1.在须要装配到其余bean中的类中加入@Component注解ui
package study.spring.configure.auto; import org.springframework.stereotype.Component; /** * 第一步:将该类声明成一个组件类,括号内的参数为组件类的id自定义名称,也能够使用@Named. * spring会自动生成该类的bean * @author wang * */ @Component("lonelyHeartsClub") public class SgtPeppers implements CompactDisc{ private String titil = "Sgt. Pepper's Lonely Hearts Club Band."; private String artist = "The Beatles"; @Override public void play() { System.out.println("Playing " + titil + " by " + artist); } }
2.开启组件扫描this
i.使用java配置开启spa
package study.spring.configure.auto; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; /* * 使用@ComponentScan注解开启组件扫描,设置扫描的基础包名 * 参数basePackages * 或者basePackageClasses */ @Configuration @ComponentScan(basePackages={"study.spring.configure.auto","study.spring.configure.auto2"}) public class CDPlayerConfig { }
ii.使用xml开启code
<?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scan base-package="study.spring.configure.auto"></context:component-scan> </beans>
3.在注入的bean中选择三种方法,使用@Autowired对bean注入component
i.在属性上直接注入xml
ii.在构造方法上注入blog
iii.在Set方法上注入
package study.spring.configure.auto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class CDPleayer { @Autowired private CompactDisc cd; public CompactDisc getCd() { return cd; } /* * 不一样的注入方法 * 1. set方法注入 * 2. 构造器注入 * 3. 属性上直接注入 * * @Autowired与@Inject相似 */ @Autowired public void setCd(CompactDisc cd) { this.cd = cd; } @Autowired(required=false) public CDPleayer(CompactDisc compactDisc) { this.cd = compactDisc; } public void play(){ cd.play(); } }
注:能够在任何方法上使用@Autowired注入
虽然自动注入很方便,可是自动注入须要自动建立bean实例,可是对于第三方的jar包中的类文件而言,不能直接使用注解进行声明为组件,所以还须要xml配置。