Spring 开发之组件赋值的实现方法
1.@Value&@PropertySource
1.1使用方式
@PropertySource:读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置文件的值
@Value:赋值
- 基本数值
- 可以写SpEL,#{}
- 可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)
1.2代码
1.Person
@Data @Slf4j @ToString publicclassPerson{ @Value("#{001+001}") privateLongid; @Value("zs") privateStringname; @Value("${person.address}") privateStringaddress; @Value("${person.age:19}") privateIntegerage; }
2.SpringConfig
@Configuration @PropertySource(value="classpath:person.properties") publicclassSpringConfig{ @Bean publicPersonperson(){ returnnewPerson(); } }
3.PropertiesTest
publicclassPropertiesTest{ publicstaticvoidmain(String[]args){ AnnotationConfigApplicationContextcontext=newAnnotationConfigApplicationContext(SpringConfig.class); Personperson=context.getBean(Person.class); System.out.println(person); //Person(id=2,name=zs,address=上海市,age=19) } }
2.@Profile
2.1使用方式
@Profile:指定组件在哪个环境的情况下才能被注册到容器中,不指定,任何环境下都能注册这个组件
加了环境标识的bean,只有这个环境被激活的时候才能注册到容器中。默认是default环境
写在配置类上,只有是指定的环境的时候,整个配置类里面的所有配置才能开始生效
没有标注环境标识的bean在任何环境下都是加载的
2.2代码
1.Message
@Data @NoArgsConstructor @AllArgsConstructor publicclassMessage{ privateStringlabel=null; }
2.SpringConfig
@Configuration publicclassSpringConfig{ @Profile("default") @Bean publicMessagedefaultMessage(){ returnnewMessage("default"); } @Profile("dev") @Bean publicMessagedevMessage(){ returnnewMessage("dev"); } @Profile("test") @Bean publicMessagetestMessage(){ returnnewMessage("test"); } @Profile("prod") @Bean publicMessageprodMessage(){ returnnewMessage("prod"); } }
3.激活方式1
激活profile:设置虚拟机参数-Dspring.profiles.active=dev,test
publicclassProfileTest{ publicstaticvoidmain(String[]args){ AnnotationConfigApplicationContextcontext=newAnnotationConfigApplicationContext(SpringConfig.class); String[]names=context.getBeanNamesForType(Message.class); for(Stringname:names){ System.out.println(name); } //devMessage //prodMessage } }
4.激活方式2
publicclassProfileTest{ publicstaticvoidmain(String[]args){ //1.创建一个AnnotationConfigApplicationContext AnnotationConfigApplicationContextcontext=newAnnotationConfigApplicationContext(); //2.设置需要激活的环境 context.getEnvironment().setActiveProfiles("dev","prod"); //3.注册主配置类 context.register(SpringConfig.class); //4.刷新容器 context.refresh(); String[]names=context.getBeanNamesForType(Message.class); for(Stringname:names){ System.out.println(name); } //testMessage //prodMessage } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。