提交 f1a989c5 编写于 作者: 武汉红喜's avatar 武汉红喜

profile

上级 4b7abb07
package org.hongxi.whatsmars.spring.profile;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Profile("prod")
@Component
public class ConditionalOnProfile implements InitializingBean {
@Value("${profile}")
private String profile;
@Override
public void afterPropertiesSet() throws Exception {
System.out.println(profile);
}
}
package org.hongxi.whatsmars.spring.profile;
import org.springframework.util.StringUtils;
public class ProfileUtils {
private static final String PROFILE_ENV_NAME = "PROFILE";
private static final String DEFAULT_PROFILE = "test";
public static String getProfile() {
String profile = System.getProperty(PROFILE_ENV_NAME);
return StringUtils.isEmpty(profile) ? DEFAULT_PROFILE : profile;
}
}
package org.hongxi.whatsmars.spring.profile;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
@Configuration
public class PropertyConfiguration {
@Bean
public PropertyPlaceholderConfigurer configurer() {
PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
String path = String.format("application-%s.properties", ProfileUtils.getProfile());
configurer.setLocation(new ClassPathResource(path));
return configurer;
}
}
package org.hongxi.whatsmars.spring.profile;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Reader implements InitializingBean {
@Value("${profile}")
private String profile;
@Override
public void afterPropertiesSet() throws Exception {
System.out.println(profile);
}
}
package org.hongxi.whatsmars.spring.profile;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestSpring {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(PropertyConfiguration.class);
context.scan("org.hongxi.whatsmars.spring.profile");
context.getEnvironment().setActiveProfiles(ProfileUtils.getProfile());
context.refresh();
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册