且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring将自动装配对象传递给类构造函数

更新时间:2023-11-12 13:28:34

Spring只能在创建对象并通过构造函数初始化后的后自动连接字段.

Spring can only ever autowire a field after an object has been created and initialized through a constructor.

按您的时间

public Crud(){                                                                 
    dataSources.put("client", new Database(clientDataSource));
    dataSources.put("admin", new Database(adminDataSource));
}

在构造函数中,Spring不可能自动连接两个字段.

in the constructor, it is impossible for Spring to have autowired the two fields.

要么使用@PostConstruct初始化方法,要么使用构造函数注入将数据源注入到构造函数中.

Either use a @PostConstruct init method or use constructor injection to inject the data sources into the constructor.