1.类的自动监测及Bean的注册
Spring 可以自动监测类并注册Bean 到ApplicationContext中
为了能够监测这些类并注册相应的Bean,需要下面内容
<context:component-scan base-pakcage="org.example" >
默认情况下,类呗自动发现并注册bean的条件是:使用@Component,@Repository ,@Service, @Controller注解或者使用@Component的自定义注解
2.
扫描过程中组件被自动监测,那么Bean名称是由BeanNameGenerator生成的 (@Component, @Repository,@Service, @Controller都会有个name属性用于显示设置Bean Name)
默认的是类名,第一个字母小写
3.
通常情况下自动查找的Spring组件,其scope是singleton 。 Spring2.5提供了一个标识scope的注解@Scope, 可以指定@Scope("prototype")
bean
package annotation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
//@Component("bean")
@Scope
@Component
public class BeanAnnotation {
public void say(String arg) {
System.out.println("BeanAnnotation : " + arg);
}
}
spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
<context:component-scan base-package="annotation"></context:component-scan>
</beans>
测试
package test.annotation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import annotation.BeanAnnotation;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestBeanAnnotation{
private ClassPathXmlApplicationContext context;
@Test
public void testBean(){
context = new ClassPathXmlApplicationContext("spring-annotation.xml");
BeanAnnotation ba = (BeanAnnotation) context.getBean("beanAnnotation");
ba.say("11");
}
}