IOC(声明bean的注解)
1,@Component
可以使用此注解描述Spring中的Bean,它是一个泛化的概念,表示一个组件(Bean),可以作用在任何层次。使用时只需要将该注解标注在相应的类上即可。
2,@Repository
用于将数据访问层(DAO层)的类标识为Spring中的Bean,其功能与@Component相同。
3,@Service
用于将业务层(Service层)的类标识为Spring中的Bean,其功能与@Component相同。
4,@Controller
用于将控制层的类标识为Spring中的Bean,其功能与@Component相同。
拓展:@Mapper是mybatis自身带的注解。也是用于DAO层的注解,不过需要在xml绑定namespace,和在主启动类配合@MapperScan使用
DI(注入bean的注解)
1,@Autowired
用于对Bean的属性变量,属性的Set方法以及构造方法进行标注,配合对应的注解处理器完成Bean的自动配置工作。默认按照Bean的类型(type)进行装配。
2,@Resource
作用与@Autowired一样。区别在于@Autowired默认按照Bean类型(type)注入,而@Resource默认按照Bean实例名称进行装配
@Resource 中有两个重要属性:name 和 type。
Spring 将 name 属性解析为 Bean 实例名称,type 属性解析为 Bean 实例类型。如果指定 name 属性,则按实例名称进行装配;如果指定 type 属性,则按 Bean 类型进行装配。
如果都不指定,则先按 Bean 实例名称装配,如果不能匹配,则再按照 Bean 类型进行装配;如果都无法匹配,则抛出 NoSuchBeanDefinitionException 异常。
3,@Qualifier
与@Autowired注解配合使用,会将默认的按照Bean类型注入改为按照Bean的实例名称装配,Bean的实例名称由@Qualifier注解的参数指定。
配置类相关注解
@Configuration 声明当前类为配置类,相当于xml形式的Spring配置(类上)
@Bean 注解在方法上,声明当前方法的返回值为一个bean,替代xml中的方式(方法上)
@Configuration 声明当前类为配置类,其中内部组合了@Component注解,表明这个类是一个bean(类上)
@ComponentScan 用于对Component进行扫描,相当于xml中的(类上)
@WishlyConfiguration 为@Configuration与@ComponentScan的组合注解,可以替代这两个注解
举例:
@Configuration
@EnableTransactionManagement // 开启事务
@MapperScan("com.wjc.product.dao")
public class MybatisConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
paginationInterceptor.setOverflow(true);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
paginationInterceptor.setLimit(1000);
return paginationInterceptor;
}
}
AOP注解
Spring支持AspectJ的注解式切面编程。
@Aspect 声明一个切面(类上)
使用@After、@Before、@Around定义建言(advice),可直接将拦截规则(切点)作为参数。
@After 在方法执行之后执行(方法上) @Before 在方法执行之前执行(方法上) @Around 在方法执行之前与之后执行(方法上)
@PointCut 声明切点
在java配置类中使用@EnableAspectJAutoProxy注解开启Spring对AspectJ代理的支持(类上)
举例:统计方法执行时间的AOP
@Component
@Aspect
public class TimerAspect {
//在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
//改包下的*类*方法**参数
@Around("execution(* com.wjc.service.Impl.*.*(..))")
public Object around(ProceedingJoinPoint jp) throws Throwable {
// System.out.println("环绕前");
// System.out.println("签名:"+jp.getSignature());
long start=System.currentTimeMillis();
//执行目标方法proceed
Object proceed = jp.proceed();
// System.out.println("环绕后");
//System.out.println(proceed);
long end=System.currentTimeMillis();
System.out.println(jp.getSignature().getName()+"耗时:"+(end-start)+"ms");
return proceed;
}
}
其他注解
@Scope 设置Spring容器如何新建Bean实例(方法上,得有@Bean)
其设置类型包括:
· Singleton (单例,一个Spring容器中只有一个bean实例,默认模式),
· Protetype (每次调用新建一个bean),
· Request (web项目中,给每个http request新建一个bean),
· Session (web项目中,给每个http session新建一个bean),
· GlobalSession(给每一个 global http session新建一个Bean实例)
@StepScope 在Spring Batch中还有涉及
@PostConstruct 由JSR-250提供,在构造函数执行完之后执行,等价于xml配置文件中bean的initMethod
@PreDestory 由JSR-250提供,在Bean销毁之前执行,等价于xml配置文件中bean的destroyMethod