1、xml
xml
配置文件方式自然需要在xml
文件中配置bean
<bean id="intelCpu" class="com.phz.entity.IntelCpu"/>
<bean id="computer" class="com.phz.entity.Computer">
<property name="intelCpu" ref="intelCpu"/>
</bean>
使用的时候需要通过
ClassPathXmlApplicationContext
对象获取。
public class MyTest {
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
Computer computer = (Computer) applicationContext.getBean("computer");
computer.play();
}
}
2、注解
Annotation
方式需要配置扫描域,且需要在使用的类最上面声明@ComponentScan("com")
,且bean
上面加上@Component
注解,需要注入bean
就添加@Resource
注解,获取bean
的时候使用ClassPathXmlApplicationContext
类
<context:component-scan base-package="com"/>
@Component(value = "computer")
public class Computer {
}
public class MyTest {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
Computer computer = (Computer) applicationContext.getBean("computer");
}
3、纯JAVA
①、ComponentScan
不需要配置
xml
文件,仅仅是将xml
文件中的ComponentScan
节点,用注解的方式配置罢了,首先还是需要在bean
上添加@Component
,在容器初始化后,再声明@ComponentScan("com")
,引导容器从com
包下扫描带有@Component
标识的类,并将其加载进入容器,在获取bean
的时候需要用AnnotationConfigApplicationContext
获取
@Component(value = "computer")
public class Computer {
}
@ComponentScan("com")
public class MyTest {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyTest.class);
Computer computer = (Computer) applicationContext.getBean("computer");
}
②、Configuration
这种方式需要配置一个全局配置类
ApplicationContextConfig
(名称随意),加上@Configuration
注解,然后下面使用@Bean
注解注入Bean
。通过此注解标注,在xml
文件中可以配置的属性,这里统统都能找到对应的注解进行配置(你也可以理解为这个类变成了Java
代码版本的XML
配置文件),读者可自行下去验证。采用这种配置,bean
便可不加@Component
注解,也不需要配置@ComponentScan
注解去主动扫描。
@Configuration
@Slf4j
public class ApplicationContextConfig {
@Bean(name = "computer")
public Computer computer() {
log.info("Computer加载进容器");
return new Computer("b");
}
@Bean(name = "intelCpu")
public IntelCpu intelCpu() {
log.info("IntelCpu加载进容器");
return new IntelCpu();
}
}
调用的时候同样是使用
AnnotationConfigApplicationContext
对象获取bean
,但是传入的参数变为ApplicationContextConfig.class
@Slf4j
public class MyTest {
@Test
public void test() {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ApplicationContextConfig.class);
Computer computer = (Computer) applicationContext.getBean("computer");
computer.play();
}
}
另一种调用方式是直接通过
@Resource
注解将我们需要的Bean
注入进来
@Slf4j
public class MyTest {
@Resource
private Computer computer;
@Test
public void test() {
computer.play();
}
}
需要注意的是,当MyTest
组件依赖Computer
,要想使用Spring
依赖注入得到组件Computer
的实例,那么MyTest
本身也要是通过Spring
的bean
来创建的才行,而不能够直接在MyTest
里面注入,上面这段代码实际上是跑不通的,因为笔者在做这个Demo
的时候是将调用方法写在了测试类中,而测试类本身是没有被Spring
容器所管理,因此在运行中会报空引用异常,而不是NoSuchBean
找不到这个bean
(读者可尝试在普通Spring Web
工程下,创建一个Controller
来验证)。