您的位置:首页 > 编程语言 > Java开发

Spring核心技术(十二)——基于Java的容器配置(二)

2016-07-30 23:46 711 查看

使用
@Configuration
注解

@Configuration
注解是一个类级别的注解,表明该对象是用来指定Bean的定义的。
@Configuration
注解的类通过
@Bean
注解的方法来声明Bean。通过调用注解了
@Bean
方法的返回的Bean可以用来构建Bean之间的相互依赖关系,可以通过前文来了解其基本概念。

注入
inter-bean
依赖

@Bean
方法依赖于其他的Bean的时候,可以通过在另一个方法中调用即可。

@Configuration
public class AppConfig {

@Bean
public Foo foo() {
return new Foo(bar());
}

@Bean
public Bar bar() {
return new Bar();
}
}


在上面的例子当中,
foo
这个bean是通过构造函数来注入另一个名为
bar
的Bean的。


前面提到过,使用
@Component
注解的类也是可以使用
@Bean
注解来声明Bean的,但是通过
@Component
注解类内的Bean之间是不能够相互作为依赖的。



查找方法注入

前文中描述了一种我们很少使用的基于查找方法的注入。这个方法在单例Bean依赖原型Bean的时候尤为有效。基于Java的配置也支持这种模式。

public abstract class CommandManager {
public Object process(Object commandState) {
// grab a new instance of the appropriate Command interface
Command command = createCommand();

// set the state on the (hopefully brand new) Command instance
command.setState(commandState);
return command.execute();
}

// okay... but where is the implementation of this method?
protected abstract Command createCommand();
}


通过基于Java的配置,开发者可以创建一个
CommandManager
的自雷来重写
createCommand()
方法,这样就会查找一个新的(原型)命令对象。

@Bean
@Scope("prototype")
public AsyncCommand asyncCommand() {
AsyncCommand command = new AsyncCommand();
// inject dependencies here as required
return command;
}

@Bean
public CommandManager commandManager() {
// return new anonymous implementation of CommandManager with command() overridden
// to return a new prototype Command object
return new CommandManager() {
protected Command createCommand() {
return asyncCommand();
}
}
}


基于Java配置的内部工作原理

下面的例子展示了
@Bean
注解了的方法被调用了两次:

@Configuration
public class AppConfig {

@Bean
public ClientService clientService1() {
ClientServiceImpl clientService = new ClientServiceImpl();
clientService.setClientDao(clientDao());
return clientService;
}

@Bean
public ClientService clientService2() {
ClientServiceImpl clientService = new ClientServiceImpl();
clientService.setClientDao(clientDao());
return clientService;
}

@Bean
public ClientDao clientDao() {
return new ClientDaoImpl();
}
}


clientDao()
方法被
clientService1()
调用了一次,也被
clientService2()
调用了一次。因为这个方法创建了一个新的
ClientDaoImpl
的实例,开发者通常认为这应该是两个实例(每个服务都有一个实例)。如果那样的话,就产生问题了:在Spring中,实例化的Bean默认情况下是单例的。这就是神奇的地方了,所有配置了
@Configuration
的类都是通过
CGLIB
来子类化的。在子类当中,所有的子类方法都会检测容器是否有缓存的对象,然后在调用父类方法,创建一个新的实例。在Spring 3.2 以后的版本之中,开发者不再需要在classpath中增加
CGLIB
的jar包了,因为CGLIB的类已经被打包到
org.springframework.cglib
之中,直接包含到了spring-core的jar包之中。


当然,不同作用域的对象在
CGLIB
中的行为是不同的,前面提到的都是单例的Bean。

当然,使用
CGLIB
的类也有一些限制和特性的:

* 因为需要子类化,所以配置类不能为final的

* 配置类需要包含一个无参的构造函数



组合基于Java的配置

使用
@Import
注解

跟XML中通过使用
<import/>
标签来实现模块化配置类似,基于Java的配置中也包含
@Import
注解来加载另一个配置类之中的Bean:

@Configuration
public class ConfigA {

@Bean
public A a() {
return new A();
}

}

@Configuration
@Import(ConfigA.class)
public class ConfigB {

@Bean
public B b() {
return new B();
}
}


现在,在启动的配置当中不再需要制定
ConfigA.class
以及
ConfigB.class
来实例化上下文了,仅仅配置一个
ConfigB
就足够精确了:

public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);

// now both beans A and B will be available...
A a = ctx.getBean(A.class);
B b = ctx.getBean(B.class);
}


这种方法简化了容器的实例化,仅仅处理一个类就可以了,而不需要开发者记住大量的配置类的信息。

对导入的Bean进行依赖注入

上面的例子是OK的,但是太过简化了,在大多数场景下,Bean可能依赖另一个配置类中定义的Bean。当使用XML的时候,这完全不是问题,因为并没有编译器参与其中,开发者可以通过简单的声明
ref="someBean"就引用了对应的依赖,Spring完全可以正常初始化。当然,当使用
@Configuration`注解类的时候,Java编译器会约束配置的模型,对其他Bean的引用是必须符合Java的语法的。

幸运的是,我们解决这个问题的方法很简单,如之前所讨论的,
@Bean
注解的方法可以有任意数量的参数来描述其依赖,让我们考虑一个包含多个配置类,且其中的Bean跨类相互引用的例子:

@Configuration
public class ServiceConfig {

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

}

@Configuration
public class RepositoryConfig {

@Bean
public AccountRepository accountRepository(DataSource dataSource) {
return new JdbcAccountRepository(dataSource);
}

}

@Configuration
@Import({ServiceConfig.class, RepositoryConfig.class})
public class SystemTestConfig {

@Bean
public DataSource dataSource() {
// return new DataSource
}

}

public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SystemTestConfig.class);
// everything wires up across configuration classes...
TransferService transferService = ctx.getBean(TransferService.class);
transferService.transfer(100.00, "A123", "C456");
}


当然,也有另一种方式来达到相同的结果,记得前文提到过,注解为
@Configuration
的配置类也会被声明为Bean由容器管理的:这就意味着开发者可以通过使用
@Autowired
@Value
来注入。


开发者需要确保需要注入的依赖是简单的那种依赖。
@Configuration
类在容器的初始化上下文中处理过早或者强迫注入可能产生问题。任何的时候,尽量如上面的例子那样来确保依赖注入正确。

而且,需要特别注意通过
@Bean
注解定义的
BeanPostProcessor
以及
BeanFactoryPostProcessor
。这些方法通常应定义为静态的
@Bean
方法,而不要触发其他配置类的实例化。否则,
@Autowired
@Value
在配置类中无法生效,因为它过早的实例化了。



@Configuration
public class ServiceConfig {

@Autowired
private AccountRepository accountRepository;

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

}

@Configuration
public class RepositoryConfig {

private final DataSource dataSource;

@Autowired
public RepositoryConfig(DataSource dataSource) {
this.dataSource = dataSource;
}

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

}

@Configuration
@Import({ServiceConfig.class, RepositoryConfig.class})
public class SystemTestConfig {

@Bean
public DataSource dataSource() {
// return new DataSource
}

}

public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SystemTestConfig.class);
// everything wires up across configuration classes...
TransferService transferService = ctx.getBean(TransferService.class);
transferService.transfer(100.00, "A123", "C456");
}



在Spring 4.3中,只支持基于构造函数的注入。在4.3的版本中,如果Bean仅有一个构造函数的话,是不需要指定
@Autowired
注解的。在上面的例子当中,
@Autowired
RepositoryConfig
的构造函数上是不需要的。



在上面的场景之中,使用
@Autowired
注解能很好的工作,但是精确决定装载的Bean还是容易引起歧义的。比如,开发者在查看
ServiceConfig
配置,开发者怎么能够知道
@Autowired AccountRepository
bean在哪里声明?在代码中这点并不明显,但是也不要紧。通过一些IDE或者是Spring Tool Suite提供了一些工具让开发者来看到装载的Bean之间的联系图。

如果开发者不希望通过IDE来找到对应的配置类的话,可以通过注入的方式来消除语义的不明确:

@Configuration
public class ServiceConfig {

@Autowired
private RepositoryConfig repositoryConfig;

@Bean
public TransferService transferService() {
// navigate 'through' the config class to the @Bean method!
return new TransferServiceImpl(repositoryConfig.accountRepository());
}

}


在上面的情况中,就可以清晰的看到
AccountRepository
这个Bean在哪里定义了。然而,
ServiceConfig
现在耦合到了
RepositoryConfig
上了,这也是折中的办法。这种耦合可以通过使用基于接口或者抽象类的的方式在某种程度上将减少。看下面的代码:

@Configuration
public class ServiceConfig {

@Autowired
private RepositoryConfig repositoryConfig;

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

@Configuration
public interface RepositoryConfig {

@Bean
AccountRepository accountRepository();

}

@Configuration
public class DefaultRepositoryConfig implements RepositoryConfig {

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

}

@Configuration
@Import({ServiceConfig.class, DefaultRepositoryConfig.class}) // import the concrete config!
public class SystemTestConfig {

@Bean
public DataSource dataSource() {
// return DataSource
}

}

public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SystemTestConfig.class);
TransferService transferService = ctx.getBean(TransferService.class);
transferService.transfer(100.00, "A123", "C456");
}


现在
ServiceConfig
DefaultRepositoryConfig
松耦合了,而IDE中的工具仍然可用,让开发者可以找到
RepositoryConfig
的实现。通过这种方式,在类依赖之间导航就普通接口代码没有区别了。

选择性的包括配置类和Bean方法

通常有需求根据系统的状态来选择性的使能或者趋势能一个配置类,或者独立的
@Bean
方法。一个普遍的例子就是使用
@Profile
注解来在Spring的
Environment
中符合条件才激活Bean。

@Profile
注解是通过使用一个更加灵活的注解
@Confitional
来实现的。
@Conditional
注解表明Bean需要实现
org.springframework.context.annotation.Condition
接口才能作为Bean注册到容器中。

实现
Condition
接口仅仅提供一个
matches(...)
方法返回
true
或者
false
。如下为一个实际的
Condition
接口的实现:

@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
if (context.getEnvironment() != null) {
// Read the @Profile annotation attributes
MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
if (attrs != null) {
for (Object value : attrs.get("value")) {
if (context.getEnvironment().acceptsProfiles(((String[]) value))) {
return true;
}
}
return false;
}
}
return true;
}


更多的信息请参考
@Conditional
的Javadoc。

同时使用XML以及基于Java的配置

Spring中的
@Configuration
类的支持并不是为了100%的替代XML的配置的。SpringXML中的诸如命名空间等还是很理想的用来配置容器的方式。在那些使用XML更为方便的情况,开发者可以选择使用XML方式的配置,比如
ClassPathXmlApplicationContext
,或者是以Java为核心的
AnnotationConfigApplicationContext
并使用
@ImportResource
注解来导入必须的XML配置。

以XML为中心,同时使用配置类

比较好的方式是在Spring容器相关的XML中包含
@Configuration
类的信息。举例来说,在很多机遇Spring XML配置方式中,很容易创建一个
@Configuration
的类,然后作为Bean包含到XML文件中。下面的代码中将会在以XML为中心的配置下使用配置类。

配置类其实根本上来说只是容器中定义的Bean集合而已。在这个例子中,我们创建了个配置类叫做
AppConfig
并将其包含在了
system-test-config.xml
之中。因为存在
<context:annotation-config/>
标签,容器可以自发的识别
@Configuration
注解。

@Configuration
public class AppConfig {

@Autowired
private DataSource dataSource;

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

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

}


system-test-config.xml配置如下:

<beans>
<!-- enable processing of annotations such as @Autowired and @Configuration -->
<context:annotation-config/>
<context:property-placeholder location="classpath:/com/acme/jdbc.properties"/>

<bean class="com.acme.AppConfig"/>

<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>


jdbc.properties:

jdbc.url=jdbc:hsqldb:hsql://localhost/xdb
jdbc.username=sa
jdbc.password=


public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:/com/acme/system-test-config.xml");
TransferService transferService = ctx.getBean(TransferService.class);
// ...
}



system-test-config.xml
之中,
AppConfig
这个bean并没有声明
id
元素,当然使用id属性完全可以,但是通常没有必要,因为一般不会引用这个Bean,而且一般可以通过类型来获取,比如其中定义的
DataSource
,除非是必须精确匹配,才需要一个id属性。



因为
@Configuration
是通使用
@Component
的元注解的,所以由
@Configuration
注解的类是会自动匹配组件扫描的。所以在上面的配置中,我们可以利用这一点来很方便的配置Bean。而且我们也不需要指定
<context:annotation-config>
标签,因为
<context:component-scan>
会使能这一功能。

现在的system-test-config.xml如下:

<beans>
<!-- picks up and registers AppConfig as a bean definition -->
<context:component-scan base-package="com.acme"/>
<context:property-placeholder location="classpath:/com/acme/jdbc.properties"/>

<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>


以配置类为中心,同时导入XML配置

在应用中,如果使用了配置类作为主要的配置容器的机制的话,在某些场景仍然有必要用些XML来辅助配置容器。在这些场景之中,通过使用
@ImportResource
并且就可以了。如下:

@Configuration
@ImportResource("classpath:/com/acme/properties-config.xml")
public class AppConfig {

@Value("${jdbc.url}")
private String url;

@Value("${jdbc.username}")
private String username;

@Value("${jdbc.password}")
private String password;

@Bean
public DataSource dataSource() {
return new DriverManagerDataSource(url, username, password);
}

}


properties-config.xml中的配置:

<beans>
<context:property-placeholder location="classpath:/com/acme/jdbc.properties"/>
</beans>


jdbc.properties
jdbc.url=jdbc:hsqldb:hsql://localhost/xdb jdbc.username=sa jdbc.password=


代码中就可以通过
AnnotationConfigApplicationContext
来配置容器了:

public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
TransferService transferService = ctx.getBean(TransferService.class);
// ...
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: