Spring学习6(6)
基于Java类的配置
使用Java类提供Bean的定义信息
?普通的PoJo只要标注了@Configuration
注解就可以为Spring容器提供Bean的定义信息,每个标注了@Bean
的方法都相当于提供了一个Bean的定义信息代码如下:
package com.smart.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class AppConf{
@Beanpublic UserDao userDao() {
return new UserDao();}@Beanpublic LogDao logDao() {
return new LogDao();}@Beanpublic LogonService logonService() {
LogonService logonService = new LogonService();logonService.setLogDao(logDao());logonService.setUserDao(userDao());return logonService;}
}
?使用Bean的类型由方法返回值决定,名称默认和方法名相同,也可以通过入参显示的只当Bean的id如@Bean(name="userDao")
。@Bean
所标注的方法提供了Bean的实例化逻辑。
?如果Bean在多个@Configuration
配置类中定义,如何引用不同配置类中定义的Bean呢?例如UserDao和LogDao在DaoConfig中定义,logonService在ServiceConfig中定义:
package com.smart.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class Daoconfig{
@Beanpublic UserDao userDao() {
return new UserDao();}public LogDao logDao(){
return new LogDao();}
}
?需要知道的是@Configuration
本身已经带有@Component
了,所以其可以像普通Bean一样注入其他Bean中。ServiceConfig的代码如下:
package com.smart.conf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;@Configuration
public class ServiceConfig{
@Autowiredprivate Daoconfig daoConfig;@Beanpublic LogonService logonService() {
LogonService logonService = new LogonService();logonService.setLogDao(daoConfig.logDao());logonService.setUserDao(daoConfig