Java:
1.8
javaMaven:
3
springSpringFramework版本以及各组件成员:
5.1.1.RELEASE
this
- spring-context
- spring-core
- spring-beans
@Primary
表示当多个bean能够自动装配到单值依赖项时,应该优先选择特定的bean。若是候选者中只存在一个主bean,则它将成为自动装配的值。code
电影的Bean类:
Movie
. 将会有两个MovieBean
, 而咱们须要播放第一场电影 - 动做片. 接下来才是喜剧片.component
Movie.java
package yag; import org.springframework.context.annotation.Configuration; @Configuration public class Movie { private String content; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Movie(){ } }
MovieShower.java
package yag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; @Configuration public class MovieShower { private Movie movie; // 注入Movie实例 @Autowired public void setMovie(Movie movie) { this.movie = movie; } // 使用实例 public void show(){ // 播放影片内容 System.out.println(movie.getContent()); } }
MovieConfig.java
package yag; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; @Configuration public class MovieConfig { @Bean @Primary public Movie firstMovie(){ // 用了这个方法来替代XML配置中的value属性以赋固定值. Movie movie = new Movie(); movie.setContent("正在播放动做片"); return movie; } @Bean public Movie secondMovie(){ Movie movie = new Movie(); movie.setContent("正在播放喜剧电影"); return new Movie(); } // BeanUser @Bean public MovieShower movieShower(){ return new MovieShower(); } }
spring-beans.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"> <context:annotation-config/> <context:component-scan base-package="yag"/> </beans>
package yag; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Runner { public static void main(String[] args){ ApplicationContext c = new AnnotationConfigApplicationContext(MovieConfig.class); MovieShower shower = c.getBean(MovieShower.class); shower.show(); } }
正在播放动做片 Process finished with exit code 0