且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

春季:在外部添加属性文件

更新时间:2023-11-16 15:48:16

可能您正在寻找的是Profiles(@Profile or @Conditional)

Probably what you are looking for is Profiles( @Profile or @Conditional )

第1步:创建个人资料.以下是产品概要文件的示例.同样,您可以为devqa

Step1: Create a profile. The following is the example for prod profile. Similarly, you can create one for dev and qa

import javax.activation.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jndi.JndiObjectFactoryBean;

@Configuration
@Profile("prod")
@PropertySource("classpath:/com/<SomePath>/app.properties")
public class ProductionProfileConfig {

    @Autowired Environment env;

    @Bean
    public DataSource dataSource() {
        JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
        jndiObjectFactoryBean.setJndiName(env.getProperty("dbName"));
        jndiObjectFactoryBean.setResourceRef(true);
        jndiObjectFactoryBean.setProxyInterface(javax.sql.DataSource.class);
        return (DataSource) jndiObjectFactoryBean.getObject();
    }
}

第2步激活配置文件

Spring在确定哪些配置文件时会采用两个独立的属性 处于活动状态:spring.profiles.activespring.profiles.default.如果 设置spring.profiles.active,然后其值确定哪个 配置文件处于活动状态.但是,如果未设置spring .profiles.active,则 Spring看起来是spring.profiles.default.如果两者都不 设置spring.profiles.active或spring.profiles.default,然后在那里 没有有效的配置文件,只有那些未定义为 在个人资料中创建

Spring honors two separate properties when determining which profiles are active: spring.profiles.active and spring.profiles.default. If spring.profiles.active is set, then its value determines which profiles are active. But if spring .profiles.active isn’t set, then Spring looks to spring.profiles.default. If neither spring.profiles.active nor spring.profiles.default is set, then there are no active profiles, and only those beans that aren’t defined as being in a profile are created

更新

如果文件位于打包的war之外,请使用PropertyConfigurator.configure(Loader.getResource(<your-file-path>));.稍后,您可以简单地使用@Value or SPel

Use PropertyConfigurator.configure(Loader.getResource(<your-file-path>)); if the file is located outside the packaged war. Later you can simply inject values using @Value or SPel