Spring Boot属性自动装配未生效

huangapple go评论76阅读模式
英文:

Spring boot property autowiring not working

问题

我有一个Spring Boot 2.3.3.RELEASE项目。

主应用程序类,

@SpringBootApplication()
public class TestApplication {
   ...
}
@ConfigurationProperties(prefix = "test")
public class TestProperties {
  ...
}
@Configuration
@EnableConfigurationProperties({TestProperties.class})
public class TestConfiguration {

}
@Service
public class AmazonEmailService {

    private final AmazonSimpleEmailService client;

    @Autowired
    private TestProperties props;

    public AmazonEmailService() {
      props.getEmail(); // 这里 props 是 null ...
    }

}

在这里,AmazonEmailService 中的 TestProperties 自动装配为 null。不确定缺少了什么。

其他类中的自动装配是正常的。

英文:

I have a Spring boot 2.3.3.RELEASE project.

Main Application class,

    @SpringBootApplication()
    public class TestApplication {
           ...
    }
    
    @ConfigurationProperties(prefix = "test")
    public class TestProperties {
      ...
    }
    
    @Configuration
    @EnableConfigurationProperties({TestProperties.class})
    public class TestConfiguration {
    
    }

@Service
public class AmazonEmailService {

	private final AmazonSimpleEmailService client;
	
	@Autowired
	private TestProperties props;

	public AmazonEmailService() {
      props.getEmail(); // Here props is null ...
    }

}

Here, TestProperties autowiring is null in AmazonEmailService. Not sure what is missing.

Other Autowiring works in other classes.

答案1

得分: 3

能否在构造函数上使用 @Autowired

private TestProperies props;

@Autowired
public AmazonEmailService(TestProperties props){
   this.props=props;
   props.getEmail(); //现在可以了。
}

这是因为在属性上使用 @Autowired 时,Spring 会在对象创建之后注入该值。但在您的情况下,您尝试在构造函数内部使用 props。在那时,它仍然为 null。

英文:

Can you use @Autowired on the constructor instead?

private TestProperies props;    

@Autowired
public AmazonEmailService(TestProperties props){
   this.props=props; 
   props.getEmail(); //Ok now.
}

This is because using @Autowired on property, Spring inject the value AFTER object create. But in your case, you try to use the props inside the contructor. At that moment, it's still null

答案2

得分: 0

在TestProperties类上添加@Component注解。

英文:

Add @Component annotation on TestProperties class

huangapple
  • 本文由 发表于 2020年9月9日 12:28:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63804750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定