将bean xml转换为spring boot注释

时间:2018-09-17 19:55:42

标签: java spring spring-boot

我有来自spring框架的以下bean xml。现在,我们将使用所有注释进行Spring Boot。如何将以下bean转换为注释?

<bean id="testPool" class="com.v1.testPoolImpl" init-method="init" destroy-method="shutdown">
    <property name="configurations">
        <bean class="org.springframework.beans.factory.config.PropertiesFactoryBean">
            <property name="location" value="classpath:database.properties"/>
        </bean>
    </property>
</bean>

com.v1.testPoolImpl(是其他一些库)

2 个答案:

答案 0 :(得分:1)

您可以创建新的Configuration类。 您可以使用注解<bean>重写@Bean,然后创建new类实例,并使用设置器来设置变量。

@Configuration
public class Config {

    @Bean(initMethod = "init" , destroyMethod = "shutdown")
    public Object testPool(){
        testPoolImpl testPool = new testPoolImpl();
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation( new ClassPathResource("database.properties"));
        propertiesFactoryBean.afterPropertiesSet();

        testPool.setConfigurations(propertiesFactoryBean.getObject());

        return testPool;
    }
}

答案 1 :(得分:0)

在Spring Boot中,您可以在运行jar文件时使用以下命令通过命令行指定属性文件:

java -jar app.jar --spring.config.location=classpath:/another-location.properties

或者,您可以在javaConfig文件上使用@PropertySource注释来提及属性文件。因此,将是这样的:

@PropertySource("classpath:my-app.properties")
public class PropertiesWithJavaConfig {
    //...
}

希望这会有所帮助。