概述:
Sring 一些新特性:
- Spring profile : 让bean活起来
- 条件化的bean声明:过滤bean
- 自动装配与歧义性: 请给我一个精准的bean
- bean的作用域: 正确行使的权利
- SpringEL表达式: Spring自己的语言
1.spring profile
profile 简单解释就是根据需求创建bean
package learn.chapter3;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jndi.JndiObjectFactoryBean;
public class ThirdDatabase {
/**
* 测试环境获取数据库
* @return
*/
@Bean(destroyMethod="shutdown")
public DataSource dataSourceE(){
return new EmbeddedDatabaseBuilder()
.addScript("classpath:schema.sql")
.addScript("classpath:test-data.sql")
.build();
}
/**
* 生产环境的数据库
* @return
*/
public DataSource dataSourceJOF(){
JndiObjectFactoryBean jndiObjectFactoryBean =
new JndiObjectFactoryBean();
jndiObjectFactoryBean.setJndiName("jdbc/myDS");
jndiObjectFactoryBean.setResourceRef(true);
jndiObjectFactoryBean.setProxyInterface(javax.sql.DataSource.class);
return (DataSource) jndiObjectFactoryBean.getObject();
}
/**
* QA环境的数据库对象
* @return
*/
public DataSource dataSourceQA(){
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl("jdbc:h2:top://dbserver/~/test");
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUsername("sa");
dataSource.setPassword("password");
dataSource.setInitialSize(20);
dataSource.setMaxActive(30);
return dataSource;
}
}
有三种数据库对象分别应用不同的场景,开发,生产,测试,多个环境,如果保证在三个环境进行切换,也就是根据需要创建不同datasource?
接下来以一个简单的例子:定义一个Fruit接口,创建三个实现类,Apple.java Peach.java Banana.java,每个人喜欢不同的水果,合理创建不同的水果
package learn.chapter3;
public interface Fruit {
void favorFruit();
}
package learn.chapter3;
public class Peach implements Fruit{
public void favorFruit() {
System.out.println("我喜欢吃桃子");
}
}
package learn.chapter3;
public class Apple implements Fruit{
public void favorFruit() {
System.out.println("我喜欢吃苹果");
}
}
package learn.chapter3;
public class Banana implements Fruit {
public void favorFruit() {
System.out.println("我喜欢吃香蕉");
}
}
然后采用两种注入方式
方式一:javaConfig
package learn.chapter3.javaConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import learn.chapter3.Apple;
import learn.chapter3.Banana;
import learn.chapter3.Fruit;
import learn.chapter3.Peach;
@Configuration
public class FruitConfig {
@Bean("fruit")
@Profile("apple")
public Fruit getApple(){
return new Apple();
}
@Bean("fruit")
@Profile("peach")
public Fruit getPeach(){
return new Peach();
}
@Bean("fruit")
@Profile("banana")
public Fruit getBanana(){
return new Banana();
}
}
总结:注意看所有的bean的名称都是fruit的,增加一个@Profile注解用来区分不同的名称
方式二:采用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"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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/util
http://www.springframework.org/schema/util/spring-util.xsd">
<beans profile="apple">
<bean id="fruit" class="learn.chapter3.Apple"></bean>
</beans>
<beans profile="peach">
<bean id="fruit" class="learn.chapter3.Peach"></bean>
</beans>
<beans profile="banana">
<bean id="fruit" class="learn.chapter3.Banana"></bean>
</beans>
</beans>
测试类:
package learn.chapter2;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import learn.chapter3.Fruit;
import learn.chapter3.javaConfig.FruitConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={FruitConfig.class})
@ActiveProfiles("peach")
public class ProfileTest {
@Autowired
private Fruit fruit;
@Test
public void favor(){
fruit.favorFruit();
}
}
总结:增加注解
@ActiveProfiles("peach") 激活对应profile,就创建不同的bean
结果:
我喜欢吃桃子
- 作为DispatcherServlet的初始化参数:
- 作为Web应用的上下文参数
- 作为环境变量
- 作为JVM的系统属性
- 集成测试直接用注解@ActiveProfiles设置
主要有两个属性: spring.profiles.active 和 spring.profiles.default
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<!-- Spring和mybatis的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>apple</param-value>
</context-param>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<init-param>
<param-name>spring.profiles.default</param-name>
<param-value>peach</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
总结:第一个是基于web,第二个基于servlet,多个不同profile可用逗号隔开,例如 peach,apple(同类不过没有必要)
2.条件化的Bean
@Conditional(实现condition接口的实现类),不同于profile,这个更加宽泛,自由
利用Conditional注解实现成年人才能创建网吧对象,模拟成年人大于等于18才能进入网吧
package learn.chapter3;
public class Person {
public int age;
public String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package learn.chapter3;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class IsAdult implements Condition {
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConfigurableListableBeanFactory ss = context.getBeanFactory();
//判断是否有Person的bean
Person p = (Person) ss.getBean("person");
if(null != p && p.getAge()>=18) {
return true;
}
return false;
}
}
这个类实现Condition接口
package learn.chapter3.javaConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import learn.chapter3.InternetBar;
import learn.chapter3.IsAdult;
import learn.chapter3.Person;
@Configuration
public class InternetBarConfig {
@Bean
public Person person(){
return new Person(19, "小明");
}
@Bean
@Conditional( IsAdult.class)
public InternetBar internetBar(){
return new InternetBar();
}
}
在注入InternetBar增加了条件类(IsAdult.class) 返回true 才创建这个bean
测试类:
package learn.chapter2;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import learn.chapter3.InternetBar;
import learn.chapter3.javaConfig.InternetBarConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={InternetBarConfig.class})
public class ConditionTest2 {
@Autowired
private InternetBar internetBar;
@Test
public void isNullInternetBar(){
assertNotNull(internetBar);
}
}
总结:当前Person未实例化,或者age<18都会报错。