dex*_*lin 7 java spring autowired spring-boot
我在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;
}
Run Code Online (Sandbox Code Playgroud)
HomeController(@Autowired works):
package com.example.myproject.controller;
@Controller
class HomeController {
@Resource
MyRepository myRepository;
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我没有得到SOAPConfiguration,但是当我尝试访问它时,我的应用程序因空指针异常而中断.
我已经在这里阅读了许多线程并且用Google搜索,但还没有找到解决方案.我试图提供所有必要的信息,如果有任何遗漏,请告诉我.
sin*_*ohn 10
我猜你init()在自动装配之前打电话.init()使用@PostConstruct进行注释,使其在所有弹簧自动装配后自动调用.
编辑:看到你的评论后,我想你是用它来创建的new MyServiceImpl().这将从Spring中取消对MyServiceImpl的控制并将其提供给您.在这种情况下,自动装配不起作用
| 归档时间: |
|
| 查看次数: |
29460 次 |
| 最近记录: |