spring中context:component-scan标签

Spirng容器通过context:component-scan标签扫描其base-package标签属性值指定的包及其子包内的所有的类并实例化被@Component、@Repository、@Service或@Controller等注解所修饰的类。

@Component:基本注解
@Respository:持久层(一般为dao层)注解
@Service:服务层或业务层(一般为service层)注解
@Controller:控制层(一般为controller层)注解

默认情况下Spring依据默认命名策略为通过注解实例化的对象命名:类名第一个字母小写. 也可以在注解中通过@Component、@Repository、@Service或@Controller 注解的value属性标识名称。

要使用这个标签,首先要引包:spring-aop-4.3.10.RELEASE.jar(自行百度,或看我的博客:初识Spring中有提到)

以一个Student类来举例:

@Component
public class Student{
	private Date now;
	
	public void setNow(Date now){
		this.now=now;
	}
	public Date getNow(){
		return now;
	}
}

在xml文件中先在Namespaces中将context选项勾上,然后如下:

	<bean class="java.util.Date"></bean>
	<!--base-package的值为要扫描的包,则这个包中,所有带有所需注解的类都会被实例化-->
	<context:component-scan base-package="com.jd"></context:component-scan>
	

我们再写个Test类测试一下:

public class Test{	
	public static void main(String[] args){
		ClassPathXmlApplicationContext classPathXmlApplictionContext = new ClassPathXmlApplicationContext("application.xml");
		Student student = classPathXmlApplicationContext.getBean(Student.class);
		System.out.println(student.getNow());
	}
}

base-package标签属性属性值:
a、Spring 容器将会扫描该属性值指定包及其子包中的所有类;
b、该属性值支持通配符,例如“com.lq..imp”表示扫描诸如com.lq.book.imp包及其子包中的类;
c、当需要扫描多个包时, 使用逗号分隔;
d、resource-pattern标签属性可以指定Spring容器仅扫描特定的类而非基包下的所有类,比如resource-pattern="/*.class"表示只扫描基包下的类,基包的子包不会被扫描。

context:component-scan子标签:
1、<context:include-filter> 子标签设定Spring容器扫描时仅扫描哪些expression指定的类,该子标签需要和context:component-scan父标签中的use-default-filters属性一起使用;
2、<context:exclude-filter> 子标签设定Spring容器扫描时不扫描哪些expression指定的类;

发布了101 篇原创文章 · 获赞 3 · 访问量 2253

猜你喜欢

转载自blog.csdn.net/S_Tian/article/details/103865488
今日推荐