2014-10-20 159 views
6

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

Application.java(@Autowired作品):

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作品):

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,但我的应用程序打破空指针异常,当我尝试访问它。

我已经在这里阅读了许多主题,并且搜索了一些内容,但是还没有找到解决方案。我试图提供所有必要的信息,请让我知道是否有遗漏。

+0

从哪里调用'init'方法?我怀疑构造函数。 – 2014-10-20 08:49:23

+0

log.info打印:启动init,soapConfiguration:null – dexBerlin 2014-10-20 08:51:18

+0

HomeController.update创建一个新的MyServiceImpl并调用myService.update,它调用它的init方法。 – dexBerlin 2014-10-20 08:53:36

回答

8

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

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

+0

我添加了@PostContruct注释,但soapConfiguration仍然为空。 – dexBerlin 2014-10-20 08:57:30

+0

查看编辑答案 – sinu 2014-10-20 08:58:40

+0

非常感谢,这解决了我的问题。 – dexBerlin 2014-10-20 09:03:24

1

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

@Configuration 
public class SomeConfiguration{ 

    @Bean 
    public SOAPConfiguration createSOAPConfiguration(){ 

     return new SOAPConfiguration(); 
    } 

} 

public class SomeOtherClass{ 

    @Autowired 
    private SOAPConfiguration soapConfiguration; 
} 
+0

Application.java应该这样做?在我的解释中? – dexBerlin 2014-10-20 08:55:36

+0

您确定您的Application.java上的方法调用了SOAPConfiguration吗? – furkan3ayraktar 2014-10-20 09:00:15