2015-09-26 73 views
-1

我不知道如何以編程方式創建bean。 這是其在.xml配置如何製造:如何在Spring Boot中以編程方式創建@Bean

<bean id="mailSender"       
class="org.springframework.mail.javamail.JavaMailSenderImpl"> 
<property name="host" value="mail.mycompany.com"/> 
</bean> 

<!-- this is a template message that we can pre-load with default state --> 
<bean id="templateMessage" 
class="org.springframework.mail.SimpleMailMessage"> 
<property name="from" value="[email protected]"/> 
<property name="subject" value="Your order"/> 
</bean> 

<bean id="orderManager" 
class="com.mycompany.businessapp.support.SimpleOrderManager"> 
<property name="mailSender" ref="mailSender"/> 
<property name="templateMessage" ref="templateMessage"/> 
</bean> 

我知道,它必須是這樣的,但我不知道如何去完成它:

@Configuration 
public class MailSender { 

@Bean 
public JavaMailSenderImpl mailSender(){ 

} 

@Bean 
public SimpleMailMessage template(){ 

} 

@Bean 
public SimpleOrderManager orderManager(){ 

} 

} 
+0

據我瞭解,你要使用標註來指定豆? (不是編程,不是在運行時)配置 http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html http://stackoverflow.com/questions/317687/how-can-i-inject-a-property-value-into-a-spring-bean-which-was-configured-using http://docs.spring.io/spring/docs/current/javadoc- api/org/springframework/beans/factory/annotation/Value.html – Vovka

回答

0

假設建議已經爲麥製成lSender和templateMessage

@Configuration公共類MailSender {

@Bean公共JavaMailSender mailSender(){ JavaMailSenderImpl IMPL =新JavaMailSenderImpl(); impl.setHost(「mail.mycompany.com」); return impl; ();}}}}}}}}}}}公共SimpleMailMessage templateMessage(){0} {0} {0} SimpleMailMessage消息= new SimpleMailMessage(); message.setFrom(「[email protected]」); message.setSubject(「Your order」); 返回消息; }

怎麼樣:

@Bean 
    public SimpleOrderManager orderManager(){ 
     return new SimpleOrderManager(mailSender(), templateMessage()); 
    } 

,或者如果您使用SimpleOrderManager制定者:

@Bean 
public SimpleOrderManager orderManager(){ 
    SimpleOrderManager orderManager = new SimpleOrderManager(); 

    orderManager.setMailSender(mailSender()); 
    orderManager.setTemplateMessage(templateMessage()); 

    return orderManager; 
} 
1

它利用這個樣子:

@Configuration 
public class MailSender { 

    @Bean 
    public JavaMailSender mailSender() { 
     JavaMailSenderImpl impl = new JavaMailSenderImpl(); 
     impl.setHost("mail.mycompany.com"); 
     return impl; 
    } 

    @Bean 
    public SimpleMailMessage template() { 
     SimpleMailMessage message = new SimpleMailMessage(); 
     message.setFrom("[email protected]"); 
     message.setSubject("Your order"); 
     return message; 
    } 
} 

我希望它會幫助你;-)

+0

thx。但是orderManager有什麼參考? – 5er

+0

我不能給出答案,這不是一個公共的API:com.mycompany.businessapp.support.SimpleOrderManager –

+0

我給你投票了。 – 5er