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是真的假的,wepoker怎么提高运气,好像是有挂(有挂方略)辅助器是一种具...
解密关于!HH平台挂,hhpo... 解密关于!HH平台挂,hhpoker到底可以作弊码,真是真的是有挂(有挂方法)1、解密关于!HH平台...
三分钟了解!拱趴大菠萝怎么开挂... 三分钟了解!拱趴大菠萝怎么开挂,epoker透视底牌,竟然存在有挂(有挂总结)1、三分钟了解!拱趴大...
一分钟揭秘!aapoker能控... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏中打...
推荐一款!htx矩阵wepok... 推荐一款!htx矩阵wepoker辅助,德州之星扫描器,竟然真的有挂(有挂透明挂);进入游戏-大厅左...
热门推荐!德普之星app安卓版... 热门推荐!德普之星app安卓版破解版,pokemmo辅助脚本,竟然是真的有挂(讲解有挂)1、金币登录...
查到实测辅助!wejoker手... 查到实测辅助!wejoker手机版透视脚本,wepoker透视脚本安卓,确实是真的有挂(有挂秘诀);...
总算了解!wepoker养号规... 总算了解!wepoker养号规律,wepoker透视脚本是什么,好像真的有挂(讲解有挂)1、下载好透...
带你了解!wepoker破解游... 带你了解!wepoker破解游戏盒子,wepoker透视脚本免费,都是真的是有挂(今日头条)能透视中...
免费测试版!hhpoker的辅... 免费测试版!hhpoker的辅助是真的吗,哈糖大菠萝挂,原来存在有挂(有挂功能)所有人都在同一条线上...