我正在尝试创建一个实用程序类来管理跨连接到同一 LDAP 实例的多个 Spring @Service
的一些 LDAP 连接。 LDAP 部分对于这个例子来说不是那么重要,但应该有助于背景。因为这是一个实用程序类,所以我希望该类由 Spring 自动实例化,并希望该类立即使用应用程序的已配置属性进行 self 配置。然后,只要我需要使用该类,我就可以简单地调用 getConnection()
方法并接收一个完全配置的、可以使用的连接。
我将应用程序配置为能够使用 org.springframework.core.env.Environment
的注入(inject)实例来检索应用程序的属性,该属性在其他 @Service 中成功运行
类,尽管它们从未在 @Service
的构造函数中被引用。
util 类目前看起来像:
@Component
public class LdapConnectionFactory {
@Inject
private Environment env;
private LdapConnectionPool connectionPool;
public LdapConnectionFactory() {
// TODO Support empty/bad configurations
LdapConnectionConfig ldapConnectionConfig = new LdapConnectionConfig();
ldapConnectionConfig.setLdapHost(env.getProperty("ldap.hostname"));
ldapConnectionConfig.setLdapPort(env.getProperty("ldap.port", int.class));
ldapConnectionConfig.setUseTls(true);
ldapConnectionConfig.setName(env.getProperty("ldap.managerDn"));
ldapConnectionConfig.setCredentials(env.getProperty("ldap.managerPassword"));
DefaultPoolableLdapConnectionFactory poolableConnectionFactory = new DefaultPoolableLdapConnectionFactory(ldapConnectionConfig);
connectionPool = new LdapConnectionPool(poolableConnectionFactory);
}
/**
* Gives a LdapConnection fetched from the pool.
*
* @return an LdapConnection object from pool
* @throws Exception if an error occurs while obtaining a connection from the factory
*/
public LdapConnection getConnection() throws LdapException {
return connectionPool.getConnection();
}
}
运行时,Spring 初始化失败 b/c env
在类的构造函数中保持为 null,env.getProperty()
调用随后抛出 NullPointerException
s。我如何编写此类代码,以便我可以确保在实例化时(或之后立即正确注入(inject)应用程序的属性,以便我可以确定在我尝试使用该类时,connectionPool
变量已经创建和配置)?
最佳答案
在 Spring 中,您可以使用以下方式注入(inject)依赖项:
- 构造器
- 领域
- 设置方法
因此,您应该使用构造函数注入(inject)此值,而不是向字段注入(inject)值。简单的代码可能如下所示:
@Inject
public LdapConnectionFactory(Environment env) {
//rest your code
}
但是如果你不想使用构造函数注入(inject)值,你可以使用 @PostConstruct
方法。
@PostConstruct
public void init() {
//rest your code from constructor
}
关于java - 如何在 @Component 构造函数中使用 @Inject ed Spring Environment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33221999/