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

相关内容

热门资讯

透视规律"poker... 您好,pokermaster破解版这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302...
透视玄学"wepok... 透视玄学"wepoker辅助工具"详细辅助揭秘教程(一贯真的是有挂)是一款可以让一直输的玩家,快速成...
透视透视"约局吧德州... 透视透视"约局吧德州透视"详细辅助大神讲解(一贯真的有挂)是一款可以让一直输的玩家,快速成为一个“必...
透视黑科技"德普之星... 您好,德普之星怎么设置埋牌这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩...
透视系统"红龙pok... 透视系统"红龙poker辅助工具"详细辅助靠谱教程(从前真的是有挂);玩家必备必赢加哟《136704...
透视好友房"we-p... 透视好友房"we-poker有人玩吗"详细辅助曝光教程(真是存在有挂);支持多人共享记分板与复盘,通...
透视科技"hhpok... 透视科技"hhpoker软件靠谱吗"详细辅助攻略教程(确实真的是有挂)准备好在hhpoker软件靠谱...
透视挂"hhpoke... 1、透视挂"hhpoker德州机器人"详细辅助AA德州教程(总是真的有挂)2、进入游戏-大厅左侧-新...
透视模拟器"wejo... 透视模拟器"wejoker辅助软件"详细辅助插件教程(真是有挂);最新版2024是一款经典耐玩的益智...
透视辅助"wepok... 透视辅助"wepoker透视脚本安卓"详细辅助总结教程(原本是真的有挂)是一款可以让一直输的玩家,快...