-
声明bean
-
装配bean
-
使用到的注解@Component、@Configuration、@ComponentScan、@Bean、@Autowired
一、注解解释
- @Component:表明一个类会作为组件类,并告知Spring要为这个类创建bean
- @Configuration:表示这是一个配置类
- @ComponentScan:启用spring组件扫描,默认会扫描此类相同的包及其子包
- @Bean:告诉Spring这个方法将会返回一个对象,这个对象要注册为Spring应用上下文中的bean
- @Autowired:自动装配,可以用于任何方法上
二、在spring中声明bean
- 创建spring项目
- 创建接口
package com.test.spring.test1;
public interface CompactDisc {
void play();
}
- 实现CompactDisc
package com.test.spring.test1;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 使用@Component将此类声明为组件让spring为此类创建bean
*/
@Component
public class SgtPeppers implements CompactDisc {
@Override
public void play() {
System.out.println("The play");
}
}
- 创建javaConfig
package com.test.spring.test1;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* @Configuration
* @ComponentScan
* 告诉spring这是一个配置类,并开启spring组件扫描
* ComponentScan默认扫描同级及子级包,可以使用basePackages属性指定包名
* 如: @ComponentScan(basePackages="test")
*/
@Configuration
@ComponentScan
public class CDPlayerConfig {
}
- 测试
package com.test.spring.test1;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @ContextConfiguration
* 指定spring去哪里加载配置
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CDPlayerConfig.class)
public class Test1 {
@Autowired
private CompactDisc compactDisc;
@Test
public void contextLoads() {
compactDisc.play();
}
}
此处使用@Autowired自动注入,由于CompactDisc接口只有一个实现类所以可以正常注入,如果CompactDisc有多个实现类则需要自定义BeanID,@Component("xxx"),注入时注入指定的BeanID即可如:
@Autowired
private CompactDisc xxx;
三、自定义bean注入到SgtPeppers中
- 改造SgtPeppers类
public class SgtPeppers implements CompactDisc {
private List list;
public SgtPeppers (List arr){
System.out.println(arr);
this.list = arr;
}
@Override
public void play() {
System.out.println("The play:" + list.size());
}
}
- 修改javaConfig
public class CDPlayerConfig {
//使用@bean将方法返回的List注册为spring的bean
//默认beanID为方法名,可使用name属性指定beanID 如:@Bean(name="arrayList")
@Bean
public List arr(){
List list = new ArrayList();
list.add(1111);
list.add(2222);
return list;
}
}
- 测试
运行Test1,运行结果为The play:2则表示注入List成功
由于将arr注册到了spring上下文中,spring在加载组件时发现SgtPeppers创建需要List 类型的arr此时spring到上下文中查找beanID为arr的对象。
如果未找到也会创建该bean,但是使用@Autowired可能会抛出异常,可以使用required属性定义 如:@Autowired(required=false) 默认required = true