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