Spring中配置bean的注解
1.@Component:基本注解
2.@Service:一般用于服务层
3.@Repository:用于标识持久层组件,一般与数据库操作相关的bean使用此注解
4.@Controller:用于表现层
使用注解配置bean
需要用到context命名空间。
1.在声明类的时候添加注解
package com.ustc.yi.annotation.controller;
import com.ustc.yi.annotation.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
/**
* Created by Yi on 2019/5/27.
*/
@Controller
public class UserController {
public void execute(){
System.out.println("UserController execute...");
}
}
2.在xml配置文件中使用<context:component-scan>来指定要扫描的包,IOC容器会扫描该包及其子包,扫描到的包中的类如果添加了注解,IOC容器会为其生成bean,bean的名字为该类的名字首写字母小写,另外也可以在注解中指定bean的名字,如@Component("指定的bean的名字")。另外可以使用resource-pattern来指定要扫描的资源,如指定只生成带有@Repository注解的.class文件,这样不会生成其他的bean
<!--指定Spring IOC容器扫描的包-->
<!--可以通过resource-pattern指定扫描的资源-->
<context:component-scan base-package="com.ustc.yi.annotation"
resource-pattern="repository/*.class"
/>
3. 可用context:exclude-filter指定排除哪些表达式的组件
context:include-filter指定包含哪些表达式组件,需要配合use-default-filters使用 (设置为true)
使用这两个时,可以指定
type为annotation:根据注解来排除或包含哪些类
type为assignable:根据类名来排除或包含哪些类
<context:component-scan base-package="com.ustc.yi.annotation"
resource-pattern="repository/*.class"
>
<!--<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
<context:exclude-filter type="assignable" expression="com.ustc.yi.annotation.repository.UserRepository"/>-->
<context:include-filter type="assignable" expression="com.ustc.yi.annotation.repository.UserRepository"/>
</context:component-scan>