【问题标题】:Some doubts about Java Configuration of the Spring Application Context (dependency injection)Spring Application Context的Java配置的一些疑惑(依赖注入)
【发布时间】:2015-01-06 13:28:42
【问题描述】:

我正在学习 Spring Core 认证。

我知道在 Spring 中我可以使用 3 种方式配置 依赖注入

  1. Java 配置
  2. 类注释
  3. XML 配置

我对如何使用第一种依赖注入配置有一些疑问。

例如我有这样的事情:

1) 一个名为TransferServiceImpl的类:

public class TransferServiceImpl implements TransferService {

    public TransferServiceImpl(AccountRepository ar) {
        this.accountRepository = ar;
    }
    ...
    ...
    ...
}

该类包含 TransferServiceImpl() 构造函数,该构造函数将 AccountRepository 对象作为输入参数,因此 AccountRepository 是必须的依赖项注入TransferServiceImpl()

2)这是前面AccountRepository类的实现:

public class JdbcAccountRepository implements AccountRepository {
    public JdbcAccountRepository(DataSource ds) {
        this.dataSource = ds;
    }
    ...
    ...
    ...
}

所以这个类的构造函数需要一个 DataSource 对象,该对象必须被注入到 JdbcAccountRepository 类中。

然后我有一个包含依赖注入配置的配置类

@Configuration
public class ApplicationConfig{

    @Bean public TransferService transferService(){
        return new TransferServiceImpl(accountRepository());
    }

    @Bean public AccountRepository accountRepository(){
        return JdbcAccountRepository(dataSoruce());
    }

    @Bean public DataSource dataSource(){
        DataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        ...................................
        ...................................
        ...................................
    }
}

所以在我看来,它的工作方式如下:

我有两个已实现的 beans,名为 TransferServiceImplJdbcAccountRepository 以及名为 ApplicationConfig 的 配置类

在配置类中,我说当有人要求工厂创建一个 TransferService 对象时,它会自动构建其实现 TransferServiceImpl 创建并自动注入一个 JdbcAccountRepository 进入 TransferServiceImpl 构造函数。

与创建 JdbcAccountRepository 的方式相同,它会在其构造函数中注入一个 DataSource 对象。

对吗?

如果是对的,我有以下疑问:

1) 在 ApplicationConfig 类中,我还声明了 DataSource bean,但我没有实现这个类。它是 Spring 提供的一个类,我只需要设置它的属性值吗?

2) 定义在 ApplicationConfig 类中的 bean 是什么时候创建的?在应用程序启动时?我认为,在前面的示例中,如果我使用 @Bean 注释构造函数,它会在应用程序启动时创建为单例。是对的还是我错过了什么?

Tnx

【问题讨论】:

    标签: java spring dependency-injection applicationcontext


    【解决方案1】:

    1) 在 ApplicationConfig 类中,我还声明了 DataSource bean 但我没有实现这个类。它是Spring提供的一个类吗? 我只需要设置它的属性值吗?

    是的。 Spring 提供了许多DataSource 实现。例如:DriverManagerDataSourceSingleConnectionDataSource 等。

    2) 定义在 ApplicationConfig 中的 bean 何时创建 班级?在应用程序启动时?我认为,在之前 例如,如果我使用 @Bean 注释一个构造函数,它被创建为 应用程序启动时的单例。是对的还是我错过了 什么?

    默认情况下,当 Spring 容器实例化时会创建 bean(如果应用程序是这样连接的,通常在启动时)。但是,您可以通过使用 @Lazy 注释来更改此行为,其中只有在明确请求时才会创建 bean。

    @Bean @Lazy public TransferService transferService(){
        return new TransferServiceImpl(accountRepository());
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 2012-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多