我正在创建pojo类并存储application.properties变量,但是我得到的是空值
注意:需要从我的Abstract类访问env
POJO类
package mynt.xyz.c4.pushnotif.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration("notificationEnvironment")
@ConfigurationProperties(prefix = "app.notif")
public class NotificationEnvironment {
private String key;
private String url;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
使用@autowired初始化类
public abstract class NotificationBase {
@Autowired
NotificationEnvironment notificationEnvironment;
public void getEnv(){
system.out.println(notificationEnvironment.getKey()); // null value
}
}
扩展到我的NotificationBaseClass的具体类
@Component
@Qualifier("androidNotification")
public class AndroidNotification extends NotificationBase implements Notification {
public AndroidNotification(String message, String title, String datalink, List<String> instanceIds) {
super(message, title, datalink, instanceIds);
}
AndroidNotification(){
super();
}
@Override
public void send() {
this.getEnv();
}
}
application.properties
app.notif.key=jkashdkjashd
app.notif.url=https/some.url
答案 0 :(得分:0)
您可以从 @Configuration
个课程中auto wire @Configuration个课程
@Configuration类可以使用@Autowired引用任何其他@Configuration类的实例。之所以有效,是因为@Configuration类本身被实例化并作为单独的Spring Bean管理。
答案 1 :(得分:0)
使您的类@Component并在@ConfigurationProperties中添加前缀值,如下所示。这对我有用,希望对您也有用。
@Component
@ConfigurationProperties(prefix = "app.notif")
public class NotificationEnvironment {
private String key;
private String url;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
您可以使用以下属性:
@Component
public class NotificationBase {
private static NotificationEnvironment notificationEnvironment;
@Autowired
public NotificationBase(NotificationEnvironment notificationEnvironment){
this.notificationEnvironment = notificationEnvironment;
}
public static void getEnv(){
System.out.println(notificationEnvironment.getKey()); // null value
}
}
答案 2 :(得分:0)
这是OP作者提到的具体的类定义之一。
public abstract class NotificationBase {
NotificationEnvironment notificationEnvironment;
public NotificationBase(NotificationEnvironment notificationEnvironment) {
this.notificationEnvironment = notificationEnvironment;
}
public void getEnv(){
System.out.println(notificationEnvironment.getKey());
}
}
更新了NotificationBase如下
@RestController
public class ArticleCommentController {
@Autowired
ConcreteNotification concreteNotification;
@RequestMapping(value = "/health_check", method = RequestMethod.GET)
public void getDemo() {
concreteNotification.getEnv();
}
}
我用来获取配置值的控制器类
Column
输出:
jkashdkjashd