Autowired字段是否在类构造期间可访问?
创始人
2024-11-12 16:30:22
0

在某些情况下,类的构造函数可能需要访问类中的@Autowired字段。然而,默认情况下,在类的构造函数被调用之前,@Autowired字段并不可用。为了解决这个问题,可以使用以下解决方案:

  1. 使用构造函数注入:

在类中声明一个有参构造函数,使用@Autowired注解该构造函数参数。在构造函数中完成对@Autowired字段的访问,这样可以确保@Autowired字段在类的构造函数中可用。

示例代码:

@Component
public class MyService {
    private final Dependency dependency;

    @Autowired
    public MyService(Dependency dependency) {
        this.dependency = dependency;
        // Access to the autowired field is available
        // within the constructor
        dependency.someMethod();
    }

    public void doSomething() {
        // Access to the autowired field is available
        // within other methods
        dependency.someMethod();
    }
}
  1. 实现InitializingBean接口:

如果类已经被Spring容器实例化,并且@Autowired字段已经设置值,可以使用InitializingBean接口完成对@Autowired字段的访问。

示例代码:

@Component
public class MyService implements InitializingBean {
    @Autowired
    private Dependency dependency;

    @Override
    public void afterPropertiesSet() throws Exception {
        // Access to the autowired field is available
        // in afterPropertiesSet method
        dependency.someMethod();
    }

    public void doSomething() {
        // Access to the autowired field is available
        // within other methods
        dependency.someMethod();
    }
}

以上两种方法都能够确保@Autowired字段在类的构造函数中可访问。

相关内容

热门资讯

解密关于!hhpoker有没有... 解密关于!hhpoker有没有作弊挂(辅助挂)总是是有挂(真的有挂)1)hhpoker有没有作弊挂有...
推荐攻略!wpk辅助器是真的吗... 推荐攻略!wpk辅助器是真的吗(辅助挂)原来真的是有挂(确实有挂)1)wpk辅助器是真的吗辅助插件:...
教程辅助!wepoker免费透... 教程辅助!wepoker免费透视脚本(辅助挂)其实真的是有挂(有挂猫腻)wepoker免费透视脚本透...
重大来袭!hhpoker可以控... 重大来袭!hhpoker可以控制牌吗(辅助挂)竟然真的有挂(有挂教程)1、玩家可以在hhpoker可...
分享开挂内幕!hhpoker是... 分享开挂内幕!hhpoker是正品吗(辅助挂)竟然真的有挂(的确有挂)1、完成hhpoker是正品吗...
热点讨论!aapoker免费透... 热点讨论!aapoker免费透视脚本(辅助挂)一直真的是有挂(确实有挂)1、首先打开aapoker免...
我来分享!hhpoker德州牛... 我来分享!hhpoker德州牛仔视频(辅助挂)果然真的有挂(有挂技巧)1、超多福利:超高返利,海量正...
科技介绍!wepoker怎么获... 科技介绍!wepoker怎么获得好牌(辅助挂)原来真的是有挂(有挂存在)1、金币登录送、破产送、升级...
让我来分享经验!wepoker... 让我来分享经验!wepoker透视器免费(辅助挂)确实是有挂(有挂教学)1、全新机制【wepoker...
热门推荐!hhpkoer辅助器... 热门推荐!hhpkoer辅助器视频(辅助挂)果然有挂(有挂透明挂)1、热门推荐!hhpkoer辅助器...