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字段在类的构造函数中可访问。

相关内容

热门资讯

WPK购买烘培!wepoekr... WPK购买烘培!wepoekr底牌透视,德州微扑克一贯存在有开挂攻略运wepoekr底牌透视辅助工具...
WPK软件指南书!wepoke... WPK软件指南书!wepoker安装教程,德州微扑克切实是真的有透视挂插件1、让任何用户在无需wep...
WPK辅助手段!智星菠萝辅助,... WPK辅助手段!智星菠萝辅助,德州微扑克总是是有辅助器技巧1、超多福利:超高返利,海量正版游戏,智星...
WPK辅助器窍要!aapoke... WPK辅助器窍要!aapoker辅助工具免费下载,德州微扑克都是存在有透视挂插件1、下载好aapok...
WPK安卓攻略!wepoker... WPK安卓攻略!wepoker究竟有没有透视,德州微扑克果然是有开挂脚本1、wepoker究竟有没有...
WPK俱乐部绝活!aapoke... WPK俱乐部绝活!aapoker透视脚本下载,德州微扑克都是是真的有辅助器神器1、用户打开应用后不用...
WPK模拟器指南书!wepok... WPK模拟器指南书!wepoker智能辅助插件,德州微扑克好像真的是有辅助app1、每一步都需要思考...
WPK模拟器方针!wepoke... WPK模拟器方针!wepoker透视最简单三个步骤,德州微扑克好像真的有开挂教程1、wepoker透...
WPK辅助器方针!wepoke... WPK辅助器方针!wepoker手机版透视脚本,德州微扑克切实真的有辅助器工具wepoker手机版透...
WPK辅助器课程!wejoke... WPK辅助器课程!wejoker私人辅助软件,德州微扑克其实真的是有辅助器攻略1、超多福利:超高返利...