Spring Boot Autowired null

时间:2014-10-20 08:47:11

标签: java spring spring-boot autowired

我在Spring Boot项目中有几个类,一些使用@Autowired,有些则不使用。我的代码如下:

Application.java(@Autowired works):

package com.example.myproject;

@ComponentScan(basePackages = {"com.example.myproject"})
@Configuration
@EnableAutoConfiguration
@EnableJpaRepositories(basePackages = "com.example.myproject.repository")
@PropertySource({"classpath:db.properties", "classpath:soap.properties"})
public class Application {

@Autowired
private Environment environment;

public static void main(String[] args) {
    SpringApplication.run(Application.class);
}

@Bean
public SOAPConfiguration soapConfiguration() {
    SOAPConfiguration SOAPConfiguration = new SOAPConfiguration();
    SOAPConfiguration.setUsername(environment.getProperty("SOAP.username"));
    SOAPConfiguration.setPassword(environment.getProperty("SOAP.password"));
    SOAPConfiguration.setUrl(environment.getProperty("SOAP.root"));
    return SOAPConfiguration;
}

HomeController(@Autowired works):

package com.example.myproject.controller;

@Controller
class HomeController {

    @Resource
    MyRepository myRepository;

MyService(@Autowired不起作用):

package com.example.myproject.service;

@Service
public class MyServiceImpl implements MyService {

    @Autowired
    public SOAPConfiguration soapConfiguration; // is null

    private void init() {
    log = LogFactory.getLog(MyServiceImpl.class);
    log.info("starting init, soapConfiguration: " + soapConfiguration);
    url = soapConfiguration.getUrl(); // booom -> NullPointerException

我没有得到SOAPConfiguration,但是当我尝试访问它时,我的应用程序因空指针异常而中断。

我已经在这里阅读了许多主题并且用Google搜索,但还没有找到解决方案。我试图提供所有必要的信息,如果有任何遗漏,请告诉我。

2 个答案:

答案 0 :(得分:9)

我猜你在自动装配发生之前打电话给init()。使用@PostConstruct注释init(),使其在所有弹簧自动装配后自动调用。

编辑:看到你的评论后,我想你是用new MyServiceImpl()创建的。这将从Spring中取消对MyServiceImpl的控制并将其提供给您。在这种情况下,自动装配不起作用

答案 1 :(得分:1)

您是否在任何配置类中为SOAPConfiguration类创建了一个bean?如果要在项目中自动装配类,则需要为其创建一个bean。例如,

@Configuration
public class SomeConfiguration{

    @Bean
    public SOAPConfiguration createSOAPConfiguration(){

        return new SOAPConfiguration();
    }

}

public class SomeOtherClass{

    @Autowired
    private SOAPConfiguration soapConfiguration;
}