Spring框架-第二弹

来源:互联网 发布:怪兽使者与少年知乎 编辑:程序博客网 时间:2024/05/22 15:59

  • 简介
  • 环境与Profile
  • 条件化Bean
  • 装饰特定的bean
  • bean的作用域

简介

主要介绍关于bean装配的更多使用方法

环境与Profile

在实际开发中,一个项目可能需要放置到不同环境进行测试,如开发环境、QA环境、生产环境等,这些环境中,部分配置不一样的?那么在进行保存项目同步时,你可能就需要修改配置环境了。显然实际开发中是不允许这种情况的发生的,那么profile就能很好的解决这个问题了。

下面以xml方式来演示这个例子

实例:

1.在spring.xml添加以下内容

<beans profile="dev">        <bean id="user4" class="cn.simfg.note.bean.User">            <property name="name" value="simfg"/>            <property name="password" value="444"/>            <property name="description" value="simfg"/>            <property name="age" value="20"/>        </bean>    </beans>    <beans profile="qa">        <bean id="user4" class="cn.simfg.note.bean.User">            <property name="name" value="simfg"/>            <property name="password" value="555"/>            <property name="description" value="simfg"/>            <property name="age" value="20"/>        </bean>    </beans>

在xml中用beans标签将在不同环境下实例化一样的bean包裹起来,注意profile属性

2.测试

测试文件是ProfileTest.java

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath:spring.xml" })@ActiveProfiles(value = {"dev"})public class ProfileTest {    @Autowired    @Qualifier("user4")    private User user;    @Test    public void testDev() {        System.out.println(user.getPassword());    }}

@ActiveProfiles(value = {“dev”}),表示将激活哪个profile

@Qualifier(“user4”),因为xml中配置了多个user,所以用这个限定符来进行标识,默认是bean的id值

运行后,便输出了444,可以修改下激活的profile,就会发现输出就会改变


当然,这只是xml方式的配置,如果是Java配置呢?

1>如果是自动注入方式的化,只需要在类上的注解添加@Profile("dev")

@Component@Profile("dev")public class User {}

2>如果是通过javaConfig配置进行实例化的,那么在对应的方法上添加注解@Profile("dev"),如果这个javaConfig全部的类都是如此,那么你可以在这个类上添加注解@Profile("dev")

@Bean@Profile("dev")public User user(){}
@Configuration@ComponentScan(basePackages = {"cn.simfg.note.bean"})@Profile("dev")public class BeanConfig {}

条件化Bean

指的就是:这又满足一定的条件(容器中包含某个bean,环境变量设置的某个变量等)才实例化这个bean。

接口:org.springframework.context.annotation.Condition
标签:@conditional()

使用:
1.首先新建一个UserCondition,其实现接口Condition,这里就不做什么条件验证了,根据实际需求出发,然后查找相关文档即可,这里就直接返回false,那就是这个User将不会被实例化

public class UserCondition implements Condition {    public boolean matches(ConditionContext conditionContext,            AnnotatedTypeMetadata annotatedTypeMetadata) {        //根据实际需求在这里面写相关的校验代码        return false;    }}

2.应用条件

@Component@Conditional(UserCondition.class)public class User {}

3.测试

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = { cn.simfg.note.config.BeanConfig.class})public class UserTest {    @Autowired(required = false)    private User user;    @Test    public void testUser2(){        if(user==null){            System.out.println("null");        }else {            System.out.println("not null");        }    }}

注意:@Autowired(required = false),需要将标签属性required设置为false,否则将无法运行

装饰特定的bean

有时候,在一个项目可能有多个不同的实例化对象,如当实现一个food接口,可能包含了meat、rice、vegetable等,那么如果装配一个food对象,那么spring将不知道选哪一个,自然就会抛出错误。

解决方法:

1.@Primary:即在一些冲突情况下首选该标签下的bean

2.@Qualifier:限定符,根据不同的限定符来确定装配哪一个

Primary,xml方式使用:

1> spring.xml

<!-- 构造法注入 -->    <bean id="user2" class="cn.simfg.note.bean.User">        <constructor-arg name="name" value="a"></constructor-arg>        <constructor-arg name="password" value="123"></constructor-arg>        <constructor-arg name="description" value="aaaa"></constructor-arg>        <constructor-arg name="age" value="20"></constructor-arg>    </bean>    <!-- setter方法注入 -->    <bean id="user3" class="cn.simfg.note.bean.User" primary="true">        <property name="name" value="b"/>        <property name="password" value="123"/>        <property name="description" value="bbbb"/>        <property name="age" value="20"/>    </bean>

注意user3的bean标签中加了一个属性primary,且设置为true

2>测试

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"classpath:spring.xml"})public class Note3Test {    @Autowired    private User user;    @Test    public void testPrimary(){        System.out.println(user);    }}

运行其中的方法你将会看到输出user3的相关信息

java方式配置,添加@Primary标签即可

@Component@Primarypublic class User {}
@Bean@Primarypublic User user(){}

限定符的使用:

其实在上文已经使用过了,那么这里就再一次简单介绍下

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"classpath:spring.xml"})public class Note3Test {    @Autowired    private User user;    @Autowired    @Qualifier("user2")    private User user2;    @Test    public void testPrimary(){        System.out.println(user);    }    @Test    public void testQualifier(){        System.out.println(user2);    }}

如果你使用xml方式配置的,因为这个id本事就是唯一的,所以就没有必要进行修改了

如果是javaConfig配置的,那么在对应的方法上加上注解@Qualifier('xxx')即可

bean的作用域

作用域类型:Singleton(单例)、Prototype(原型)、Session(会话)、Request(请求)等

这里指简单介绍下如何进行设置,至于什么时候使用什么样作用域,根据实际需求来编写即可

默认作用域:Singleton

1.xml配置,在bean标签中加上一个scope属性即可

2.javaConfig配置,在对应的类或方法上添加标签@Scope("prototype")


扫描左侧二维码,关注个人公众号:SimFG,让我们一起探索世界吧

我发现我是左右不分啊 >V<

原创粉丝点击