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

相关内容

热门资讯

透视了解!pokemmo修改器... 透视了解!pokemmo修改器手机版(透视)竟然是有辅助app(真的有挂)-哔哩哔哩1、首先打开po...
这一问题亟待解决!wepoke... 您好,wepoker辅助器安装包这款游戏可以开挂的,确实是有挂的,需要了解加去威信【48527505...
透视智能ai!pokemmo辅... 透视智能ai!pokemmo辅助器脚本下载(透视)果然存在有辅助修改器(有挂教学)-哔哩哔哩进入游戏...
于此同时!we-poker软件... 于此同时!we-poker软件(透视)确实真的有辅助平台(有挂详情)-哔哩哔哩1、we-poker软...
现场直击!wepoker私人局... 现场直击!wepoker私人局外卦(透视)总是是真的辅助工具(真是有挂)-哔哩哔哩小薇(辅助器软件下...
透视存在!德普之星辅助工具如何... 透视存在!德普之星辅助工具如何打开(透视)果然存在有辅助修改器(存在有挂)-哔哩哔哩1)德普之星辅助...
透视好牌!hhpoker德州机... 透视好牌!hhpoker德州机器人(透视)切实存在有辅助辅助器(有挂秘诀)-哔哩哔哩1、hhpoke...
透视计算!德州局怎么透视(透视... 透视计算!德州局怎么透视(透视)好像真的有辅助安装(新版有挂)-哔哩哔哩1、操作简单,无需德州局怎么...
突发!epoker透视(透视)... 突发!epoker透视(透视)竟然真的是有辅助app(有挂实锤)-哔哩哔哩1、许多玩家不知道epok...
日前!pokemmo辅助器手机... 日前!pokemmo辅助器手机版下载(透视)一直有辅助辅助器(竟然有挂)-哔哩哔哩1、进入到poke...