java - Spring Boot Autowiring null

标签 java spring spring-boot autowired

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

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

我已经在这里阅读了很多主题并进行了谷歌搜索,但还没有找到解决方案。我已尽力提供所有必要信息,如有遗漏请告知我。

最佳答案

我猜你在 Autowiring 发生之前调用了 init()。用@PostConstruct 注释 init() 使其在所有 spring Autowiring 之后自动调用。

编辑:看到您的评论后,我猜您正在使用 new MyServiceImpl() 创建它。这会从 Spring 手中夺走 MyServiceImpl 的控制权,并将其交给您。在这种情况下 Autowiring 将不起作用

关于java - Spring Boot Autowiring null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26461697/

相关文章:

java - 如何将字符串转换为 GZIP Base64 字符串?

java - 找不到要导入的项目 - Helios eclipse

java - Spring Data JPA createCountQueryFor 替换?

java - IntelliJ 中的单一单元测试无法找到 Spring .properties 文件

java - JPA/Jackson - 反序列化时排除字段并在序列化时包含它们

java - Java中的接口(interface)是什么?

spring - 正确的 mvc :interceptor configuration in Spring

java - org.springframework.expression.spel.SpelEvaluationException : EL1008E: Property or field 'latestTotalCases' cannot be found on object

java - 如何在opentelemetry中排除url(健康检查痕迹)

java - 使用服务器缓存 15 分钟