spring bean中的mailSender属性为null(autowired和setter都不工作)

时间:2015-12-11 16:09:22

标签: spring javabeans

我尝试使用mailsender发送电子邮件。为了初始化mailSender,我尝试使用@Service和@Autowired,它说mailSender为null;然后我尝试使用getter和setter,它说mailSender也是null。

我认为这可能是一个普遍的春豆问题,但我按照在线教程来设置属性。我的代码有什么问题?

public class Test {
    private org.springframework.mail.MailSender mailSender;

    public org.springframework.mail.MailSender getMailSender() {
        return mailSender;
    }

    public void setMailSender(org.springframework.mail.MailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void send() {
        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom(MyFrom);
        message.setTo(MyTo);
        message.setSubject("test");
        message.setText("test");
        mailSender.send(message);
    }
}

以下是我的beans.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://cxf.apache.org/jaxrs
    http://cxf.apache.org/schemas/jaxrs.xsd">

    <mvc:annotation-driven validator="validator" />
    <bean id="validator"        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.gmail.com" />
        <property name="port" value="587" />
        <property name="username" value="username" />
        <property name="password" value="password" />

        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
            </props>
        </property>
    </bean>
    <bean id="mailMail" class="study.hard.Test">
         <property name="mailSender" ref="mailSender" />
    </bean>

</beans>

以下是调用test.send();

的类
public class ProjectdMonitor { 
    public void alert() {
        Test test = new Test();
        test.send();
    }
}

1 个答案:

答案 0 :(得分:1)

您正在使用new运算符来创建bean,而spring并不知道这个新创建的bean。因此mailSender属性将为null。

在下面的代码中,我们从spring应用程序上下文获取Test bean,而不是使用new运算符创建。从弹簧应用程序上下文中获取,所有自动装配都会发生。

尝试以下方法:

public static void main(String args[]){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    Test test = context.getBean("mailMail", Test.class);
    test.send();
}