带注释的Spring配置文件

时间:2015-02-10 12:23:15

标签: spring annotations pom.xml

我在我的pom.xml中创建了一个配置文件

 <profiles>
    <profile>
       <id>test</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <driverClassName>com.mysql.jdbc.Driver</driverClassName>
            <databaseUrl>jdbc:mysql://localhost:3306/orgdb</databaseUrl>
            <generateDatabase>true</generateDatabase>
            <maxIdle>10</maxIdle>
            <removeAbandoned>true</removeAbandoned>
            <username>root</username>
            <password></password>
        </properties>

    </profile>


</profiles>

我想使用AppConfig类中的配置文件属性来设置我的dataSource参数:

@Bean
public DataSource dataSource(){
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/orgdb");
    dataSource.setUsername( "root" );
    dataSource.setPassword( "" );
    return dataSource;
}

然后可以在我的pom.xml中切换活动配置文件。我只能找到有关如何使用xml文件或属性文件执行此操作的信息。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我列出了我用过的相同步骤: -

  1. 创建属性文件env.properties并在AppConfig.java @PropertySource(value = { "classpath:env.properties" })
  2. 中注册
  3. 现在在你的env.properties中写下以下driverClassName=${driverClassName}等等......
  4. 在AppConfig中使用 PropertySourcesPlaceholderConfigurer 来读取属性文件,如代码段所示

    @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); }

  5. 使用您的属性文件变量,如下所示

    @Value(value = "${driverClassName}") private String driverClassName;

  6. 感谢。

相关问题