为什么@Autowired不起作用返回空指针值

时间:2019-12-21 08:53:03

标签: spring authentication smtp javabeans autowired

这是我的代码。我做错了什么?我尝试使用@Autowired摆脱  公共静态JavaMailSender emailSender = getJavaMailSender();

 @Component
    public class EmailServiceImpl{

        @Autowired
        public static JavaMailSender emailSender;


        @Bean
        public static JavaMailSender getJavaMailSender() {
            JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

            mailSender.setPassword("password");

      /**/
        return mailSender;
    }
}

1 个答案:

答案 0 :(得分:1)

例如在配置类中定义以下给出的代码:

@Configuration
public class config{
@Bean
        public static JavaMailSender getJavaMailSender() {
            JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

            mailSender.setPassword("password");

      /**/
        return mailSender;
    }
}

然后在类 EmailServiceImpl 中应用依赖项注入,例如:

@Component
    public class EmailServiceImpl{

        @Autowired
        public static JavaMailSender emailSender;


        // remaining code
}