java - 如何在 @Component 构造函数中使用 @Inject ed Spring Environment

标签 java spring dependency-injection

我正在尝试创建一个实用程序类来管理跨连接到同一 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() 调用随后抛出 NullPointerExceptions。我如何编写此类代码,以便我可以确保在实例化时(或之后立即正确注入(inject)应用程序的属性,以便我可以确定在我尝试使用该类时,connectionPool 变量已经创建和配置)?

最佳答案

在 Spring 中,您可以使用以下方式注入(inject)依赖项:

  1. 构造器
  2. 领域
  3. 设置方法

因此,您应该使用构造函数注入(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/

相关文章:

java - 当 @ApplicationScoped 注入(inject)到另一个类中时,@ApplicationScoped bean 中具有不同作用域的依赖项是否会再次重新注入(inject)?

java - 如何从 JTextField 获取 "getActionCommand"?我在调试时看到它但是

Java spring mvc : IllegalStateException: Cannot convert value of type [java. lang.String] 为所需类型

javascript - JS $http.POST 方法 405 错误

java - 如何在 spring 应用程序上下文 xml 文件中使用 pom.xml 中的属性?

spring - 使用 Java 注释使用 Spring 发送电子邮件

java - 如何在 1.6 中禁用 JTable 中的所有排序代码

java - Java 编程中的 Bean

java - 使用 Vaadin 和 Spring Boot 实现依赖注入(inject)的良好实践

angularjs - 注入(inject)的依赖项在单元测试中未定义