Spring自学第二天

1.基于注解的配置bean
  组件扫描(component scanning):Spring能够从classpath下自动扫描,侦测和实例化具有特定注解的组件
  组件包括:
  -@Component:基本注解,表示一个受Spring管理的组件
  -@Respository:标识持久层组件
  -@Service:标识服务层(业务层)组件
  -@Controller:标识表现层组件
  使用注解后,还需要在Spring配置文件中声明<context:component-scan>
  -base-package属性指定一个需要扫描的基类包,Spring容器将会扫描这个基类包及其自爆中的所有类
  -当需要扫描多个包时,使用逗号分隔
例如:一个基于注解的Bean
@Component   //受Spring管理的组件
public class testObject {
}  
新建一个接口:UserRespository
public interface UserRepository {
void save();
}
这个接口Impl,持久层
@Repository(value="userRespository")
public class UserRepositoryImpl implements UserRepository {
@Override
public void save() {
// TODO Auto-generated method stub
        System.out.println("UserRepository begin~~~~~~");
}
}  
写一个业务层
@Service
public class UserService {
public void add(){
System.out.println("UserService begin~~~~");
}
}
写一个Controller
@Controller
public class UserController {
public void executable(){
System.out.println("UserController begin");
}
}  
配置文件中配置自动扫描的包:
<context:component-scan base-package="cn.spring.study03.*" />  
-如果仅希望扫描特定的类而非基包下的所有类,可使用resource-pattern属性过滤特定的类,示例:
<context:component-scan base-package="com.spring.beans"
    resource-pattern="repository/*.class"/>
-<context:include-filter>子节点表示要包含的目标类
-<context:exclude-filter>子节点表示要排除在外的目标类
支持多种类型的过滤表达式
 annotation   com.spring.XxxAnnotation  所有标注了XxxAnnotation的类,该类型采用目标类是否标注了某个注解进行过滤
 assinable    com.spring.XxxService    所有继承或扩展XxxService的类,该类型采用目标类是否继承或扩展某个特定类进行过滤
 aspectj   com.spring.*Service+   所有类名以Service结束的类及继承或扩展它们的类。该类型采用Aspectj表达式进行过滤
 regex com.spring.anno...  所有com.spring.anno包下的类,该类型采用正则表达式根据类的类名进行过滤
 custom  com.spring.XxxTypeFilter  采用XxxTypeFilter通过代码的方式定义过滤规则。该类必须实现org.springframework.core.type.TypeFilter接口
<!--context:exclude-filter 子节点指定排除哪些指定表达式组件-->
<context:component-scan base-package="com.spring.annotation">
    <context:exclude-filter type="annotation"
        expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
注意:默认情况下ClassPathBeanDefinitionScanner会注册对@Component、@ManagedBean的bean进行扫描,因为use-default-filter默认为true
假设在一个包下包含多种注解的Bean,这里仅仅设置了需要扫描到@Controller,这是可以通过将use-default-filter设置为false即可
2.泛型依赖注入,是spring 4.0引入的新功能
一个典型的例子,首先创建BaseRepository<T>和BaseService<T>  
public class BaseRepository<T> {
}  
public class BaseService<T> {
@Autowired
protected BaseRepository<T> repository;
public void add(){
System.out.println("add...");
System.out.println(repository);
}
}  
在创建UserRepository继承BaseRepository,和UserService继承BaseService,让他们交给IOC容器处理
@Repository
public class UserRepository extends BaseRepository<User>{



@Service
public class UserService extends BaseService<User>{



配置文件即可  

  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章