自动扫描(不用每一个类都到applicationContext.xml中配置,用注解的方式进行注册)
1 引入context命名空间(在Spring的配置文件中),配置文件如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
打开配置 <context:component-scan base-package="包名(扫描本包及子包)"/>
spring 会自动扫描cn.itcast.crm包下面有注解的类,完成Bean的装配。
<!-- 配置注解自动扫描 -->
<context:component-scan base-package="cn.itcast.crm"></context:component-scan>
2 在classPath中加入注解用的jar包common-annotations.jar
-----------常用注解--------
--定义Bean的注解
@Controller
@Controller("Bean的名称")
定义控制层Bean,如Action
@Service
@Service("Bean的名称")
定义业务层Bean
@Repository
@Repository("Bean的名称")
定义DAO层Bean
@Component
定义Bean, 不好归类时使用.
--自动装配Bean(选用一种注解就可以)
@Autowired (Srping提供的)
默认按类型匹配,自动装配(Srping提供的),可以写在成员属性上,或写在setter方法上
@Autowired(required=true)
一定要找到匹配的Bean,否则抛异常。 默认值就是true
@Autowired
@Qualifier("bean的名字")
按名称装配Bean,与@Autowired组合使用,解决按类型匹配找到多个Bean问题。
@Resource JSR-250提供的
默认按名称装配,当找不到名称匹配的bean再按类型装配.
可以写在成员属性上,或写在setter方法上
可以通过@Resource(name="beanName") 指定被注入的bean的名称, 要是未指定name属性, 默认使用成员属性的变量名,一般不用写name属性.
@Resource(name="beanName")指定了name属性,按名称注入但没找到bean, 就不会再按类型装配了.
一般在接口维护一个常量,
public interface ICompanyService {
public final static String SERVICE_NAME="cn.itcast.crm.service.impl.CompanyServiceImpl";
在注入DAO对象时使用该常量表示具体的DAO实现类,这也体现了面向接口编程思想@Resource(name=ISysUserDao.SERVICE_NAME)
private ISysUserDao sysUserDao;
@Inject 是JSR-330提供的
按类型装配,功能比@Autowired少,没有使用的必要。
--定义Bean的作用域和生命过程
@Scope("prototype")
值有:singleton,prototype,session,request,session,globalSession
一般action是多例的,交由Spring管理时默认为singleton,即单例的,要加这个注解定义为prototype变成多例的
@PostConstruct
相当于init-method,使用在方法上,当Bean初始化时执行。
@PreDestroy
相当于destory-method,使用在方法上,当Bean销毁时执行。
--声明式事务
@Transactional ,其属性包括隔离级别,传播行为(多个事务相互调用时会考虑这个),只读,一般在类上设为只读,在进行增删改时才在方法进行readOnly=false,会覆盖类上的注释。
@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=false)
有多个属性