我们可以将@Autow的注释用作构造函数参数吗?

发布于 2025-02-13 05:12:32 字数 1043 浏览 0 评论 0原文

就我而言,我正在尝试使用环境类来读取属性。我尝试了两个选择。

选项1-我尝试使用@Autowired enviornment类,如下示例所示。

@Service("idmHelper")
public class IdmHelper {

    @Autowired
    Environment env;

    public IdmHelper() {
       env.getProperty('property-name')
       ...
   }
}

在这里给出nullpointerexception 。因为env为null。

选项2-我尝试使用@autowired作为参数,如下示例所示。

@Service("idmHelper")
public class IdmHelper {

    public IdmHelper(@Autowired Environment env) {
       env.getProperty('property-name')
       ...
   }
}

此处env> env将获得一个对象和我可以访问属性。但是我遇到以下错误;

在这里输入图像描述

我是Spring-Boot的新手错误。我怀疑这与启动构造函数有关。如果我错了,请纠正我。

这是我的完整代码; full-code-of-indm-helper-class

In my case I am trying to use Environment class to read properties. I tried two options.

Option 1 - I tried to use @Autowired the Enviornment class as shown in the following example.

@Service("idmHelper")
public class IdmHelper {

    @Autowired
    Environment env;

    public IdmHelper() {
       env.getProperty('property-name')
       ...
   }
}

Here it gives a NullPointerException. Becuase env is null.

Option 2 - I tried to use @Autowired inside the constructor as an argument, as shown in the following example.

@Service("idmHelper")
public class IdmHelper {

    public IdmHelper(@Autowired Environment env) {
       env.getProperty('property-name')
       ...
   }
}

Here the env will get an object and I can access the properties. But I am getting the following error;

enter image description here

I am new to spring-boot, can someone explain why I am getting this error. I doubt that it is something to do with initiating the constructor. Please correct me If I am wrong.

This is my full code;
Full-code-of-idm-helper-class

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫七 2025-02-20 05:12:32

尝试:

@Service("idmHelper")
public class IdmHelper {

    @Autowired
    Environment env;
    private var prop = null ; 

    @PostConstruct
    public init() {
       prop = env.getProperty('property-name');
   }
}

其他解决方案:

@Service("idmHelper")
public class IdmHelper {

    @Autowired 
    public IdmHelper(Environment env) {
       ...
   }
}

Try:

@Service("idmHelper")
public class IdmHelper {

    @Autowired
    Environment env;
    private var prop = null ; 

    @PostConstruct
    public init() {
       prop = env.getProperty('property-name');
   }
}

Other solution :

@Service("idmHelper")
public class IdmHelper {

    @Autowired 
    public IdmHelper(Environment env) {
       ...
   }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文