springboot获取profile的操作
⽬录
springboot获取profile
通过代码获取profile
通过注解的⽅式来获取Profile
spring profile的基本使⽤
Spring profile在我们系统中的使⽤⾮常简单
我们的问题出在哪⾥呢?
springboot获取profile
通过代码获取profile
@Component
public class ProfileUtils implements ApplicationContextAware {
private static ApplicationContext context = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
}
public static String getActiveProfile(){
String[] profiles = Environment().getActiveProfiles();
if(profiles.length != 0){
return profiles[0];
}
spring怎么读取properties
return "";
}
}
通过注解的⽅式来获取Profile
@Profile("dev","test")
//下⾯的配置信息只有在dev环境和test环境会⽣效
@Service
spring profile的基本使⽤
Spring profile是Spring 3引⼊的概念,⼀般系统开发的时候更喜欢使⽤Maven中的profile来进⾏不同环境配置⽂件的区分。Spring的profile⼀直没有怎么使⽤,最近在⼀个公司系统开发过程中同事使⽤了Spring profile。可是在设置default profile上遇到了⿇烦。跟着⼀起研究了半天,才发现了问题所在。
Spring profile在我们系统中的使⽤⾮常简单
并没有使⽤runtime的特性,只是在xml中定义了不同profile环境中的beans
<!-- other beans -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
.......
<!-- production环境 -->
<beans profile="production">
<context:property-placeholder ignore-resource-not-found="true"
location="classpath*:/application.properties" />
....
</beans>
<!-- local环境 -->
<beans profile="local">
<context:property-placeholder ignore-resource-not-found="true"
location="classpath*:/application.properties
,classpath*:/application.development.properties"/>
....
</beans>
接下来我们⼀般可以通过在l,在properties中来选择使⽤什么环境的profile,例如
<!-- l -->
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>production</param-value>
</context-param>
<!-- properties选择 -->
System.setProperty("spring.profiles.active", "development");
我们的问题出在哪⾥呢?
出在了我们想通过jndi⽽不是jvm参数来选择默认的profile,⾸先我们知道spring profile的设置不能在properties⽂件⾥,因为spring的加载顺序。我们不想改变系统的启动参数,所以选择了jndi的⽅式来读取profile的默认启动,关键来了,在配置jndi的时候我们进⾏了以下设置
<Environment name="spring.profiles.active" type="java.lang.String" value="local">
悲哀的发现不起作⽤,spring的log⾥⾯也没有任何有⽤的提⽰,还没到获取profile相关的log就因为读取不到bean挂了。只好去掉了profile相关的xml⽂件重启启动⼀次系统才发现spring默认读取的jndi名字是spring.profiles.default⽽不是
spring.profiles.active。
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。