为何要使用这个@profile注解。@profile注解是spring提供的一个用来标明当前运行环境的注解。咱们正常开发的过程当中常常遇到的问题是,开发环境是一套环境,qa测试是一套环境,线上部署又是一套环境。这样从开发到测试再到部署,会对程序中的配置修改屡次,尤为是从qa到上线这个环节,让qa的也不敢保证改了哪一个配置以后能不能在线上运行。java
为了解决上面的问题,咱们通常会使用一种方法,就是配置文件,而后经过不一样的环境读取不一样的配置文件,从而在不一样的场景中跑咱们的程序。spring
那么,spring中的@profile注解的做用就体如今这里。在spring使用DI来依赖注入的时候,可以根据当前制定的运行环境来注入相应的bean。最多见的就是使用不一样的DataSource了。app
下面详细的介绍一下,如何经过spring的@profile注解实现上面的功能。测试
主要有两种方式url
一种是直接java里面使用注解完成code
先建立javaBean(Datasource) (记得建立无参,有参构造方法和getter,setter方法)xml
public class Datasource { private String url; private String userName; private String password;
而后是java配置类对象
@Configuration //@ComponentScan("com.sxt.pojo") public class Config { @Bean @Profile("dev") public Datasource devDs(){ return new Datasource("http://dev:8080/","admin","admin"); } @Bean @Profile("pro") public Datasource proDs(){ return new Datasource("http://pro:8083/","root","root"); } }
而后测试开发
public static void main(String[] args) { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(); //设置使用哪一种环境 ac.getEnvironment().setActiveProfiles("dev"); ac.register(Config.class); ac.refresh(); Datasource ds = ac.getBean(Datasource.class); System.out.println(ds); }
以上是java方式的@profile注解的使用部署
xml配置方式的使用
一样须要Datasource这个实体类
public class Datasource { private String url; private String userName; private String password;
而后须要建立spring的配置文件 ,取名为applicationContext.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:p="http://www.springframework.org/schema/p" 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-4.3.xsd"> <beans profile="dev"> <bean class="com.sxt.pojo.Datasource"> <property name="url" value="http://dev1:8080/" /> <property name="userName" value="admin" /> <property name="password" value="admin" /> </bean> </beans> <beans profile="pro"> <bean class="com.sxt.pojo.Datasource"> <property name="url" value="http:/pro1:8081/" /> <property name="userName" value="root" /> <property name ="password" value="root" /> </bean> </beans> </beans>
而后测试
public static void main(String[] args) { ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); //设置使用哪一种环境 ac.getEnvironment().setActiveProfiles("dev"); ac.refresh(); Datasource ds = ac.getBean(Datasource.class); System.out.println(ds); }
注意java方式和xml方式初始化spring容器的方法是不一样的
java的是建立AnntotionConfigApplication对象
经过该对象的register方法获取到java的配置类 Javaconfig
在经过getBean去获取profile注解设置的名字
xml的是实例化applicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
实例化过程当中把配置文件传入 , 直接初始化spring容器 ,
而后再在经过getBean去获取profile注解设置的名字