从xml移动到Annotations

时间:2013-12-25 19:58:50

标签: java spring

我从2.5迁移到Spring 3,并希望使用注释来注入我的bean。我无法弄清楚如何创建使用注释来实现以下

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="#{configLoader.getSmtpServer()}" />
    <property name="username" value="#{configLoader.getSmtpUsername()}" />
    <property name="password" value="#{configLoader.getSmtpPassword()}" />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
        </props>
    </property>
</bean>

<!-- A properties file based configuration bean -->
<bean id="propConfiguration" class="org.apache.commons.configuration.PropertiesConfiguration">
    <property name="delimiterParsingDisabled" value="true"/>
    <property name="file" value="classpath:configuration.#{systemProperties.CONFIG_MODE}.properties"/>
    <property name="reloadingStrategy" ref="reloadingStrategy"/>
</bean>

<!-- The managed reloading strategy for the configuration bean -->
<bean id="reloadingStrategy" class="org.apache.commons.configuration.reloading.FileChangedReloadingStrategy">
    <property name="refreshDelay" value="30000"/>
</bean>

1 个答案:

答案 0 :(得分:1)

只需创建一个用@Configuration注释的bean或bean。然后就像我们的祖先在Spring之前所做的那样在Java中实例化所有内容。

例如:

@Configuration
public class MyConfig {

    @Bean
    public ReloadingStrategy reloadingStrategy() {
        strategy = new FileChangedReloadingStrategy();
        strategy.setRefreshDelay(30000);
        return strategy;
    }
}

然后对其他依赖项执行相同的操作。

要引用另一个配置类中定义的bean,只需使用@Autowired