从@controller读取Spring配置文件

时间:2018-11-28 11:51:27

标签: java spring maven spring-mvc

我想将Maven配置文件链接到弹簧配置文件。该项目建立在war文件中。该应用程序是部署在Weblogic Server中的Spring应用程序,而不是SpringBoot。

我有这个pom.xml文件

<profile>
    <id>debug</id>
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
    <properties>
        <spring.profiles.active>debug</spring.profiles.active>
    </properties>
</profile>
..

以及在应用程序@Controller中:

  @Autowired
  private Environment env;

  final List<String> activeProfiles = Arrays.asList(env.getActiveProfiles());

但是activeProfilesempty

我使用

得到了相同的结果
<activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <spring.profiles.to.activate>local</spring.profiles.to.activate>
            </properties>

1 个答案:

答案 0 :(得分:2)

您仅使用Maven配置文件定义spring.profiles.active属性值。该属性可用于Maven构建,例如用于资源过滤。

该值仍然必须传递给运行Spring Boot的JVM,例如JUnit测试通常与Maven Surefire插件一起运行,该插件会分叉JVM,如果不使用argLine配置,则不会看到属性:

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <configuration>
        <argLine>-Dspring.profiles.active=${spring.profiles.active}</argLine>
      </configuration>
    </plugin>
  </plugins>
</build>

对于用于启动Spring Boot应用程序的任何Maven插件,以上通常是正确的。