Spring注解开发

Spring注解开发

 
 

配置文件


在spring4之后,使用注解开发必须导入aop包

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/>
</beans>

 
其中<context:annotation-config/>隐式地向 Spring容器注册AutowiredAnnotationBeanPostProcessorRequiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor以及PersistenceAnnotationBeanPostProcessor这4个BeanPostProcessor

 
注:当使用<context:component-scan/>后,即可将<context:annotation-config/>省去
 
指定扫描的包,这个包下的spring注解才会生效

    <context:component-scan base-package="com.jundeng.service"/>
    <context:component-scan base-package="com.jundeng.dao"/>

 
 

Spring原始注解


@Component

将某个类注册到spring容器中,
相当于<bean id="people" class="com.jundeng.pojo.People">

可传入参数作为beanID
 

@Repository

dao层类的注解,相当于带语义的@Component
 

@Service

service层类的注解,相当于带语义的@Component
 

@Controller

controller层类的注解,相当于带语义的@Component
 

@Autowired

为某个属性或setter方法设定值

按照数据类型从Spring容器中进行匹配,自动注入到属性中
 

@Qualifier

按照传入的id值从容器中匹配,结合@Autowired一起使用
 

@Resource

为某个属性或setter方法设定值

@Resource(name = "implDao"), 相当于@Autowired+@Qualifier
 

@Value

为某个属性或setter方法设定值

普通属性值注入,相当于<property name="dog" value="123"/>

当Spring配置文件中导入了外部配置文件时,可以通过占位符传值:@Value("${key}")
 

@Scope

标识类的作用域,单例singleton, 多例prototype
 

@PostConstruct

标注某个方法使其在初始化后调用
 

@PreDestroy

标注某个方法使其在销毁前调用

注:prototype作用域的对象在Spring容器close后仍存在,所以关闭Spring容器并不会调用带有@PreDestroy的方法

 
 

Spring新注解


使用Spring新注解可以完全不通过ApplicationContext.xml
 

获取Spring容器,传入的参数为配置类的class对象:

ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);

 

@Configuration

表示当前类是一个配置类,也被Spring容器托管,因为其本身就是个 @Component,相当于ApplicationContext.xml

 

@ComponentScan(“path”)

用于配置类上指定扫描路径,spring会把指定路径下带有指定注解的类自动装配到bean容器里,会被自动装配的注解包括@Controller@Service@Component@Repository等等。

@ComponentScan("com.jundeng.pojo")相当于<context:component-scan base-package="com.jundeng.pojo"/>

 

@Bean(“name”)

注册一个bean,相当于ApplicationContext.xml中的一个bean标签,传入的值相当于bean标签中的id属性,如果未传值,则默认为这个方法的名字,返回值相当于class属性

当配置类带有@ComponentScan注解,且一个类带有@Component等标签又同时被带@Bean的方法返回时,会在IOC容器注册该类的不同对象

 

@PropertySource(“class:path”)

用于配置类,加载.properties文件的配置

 
@Import

导入其它配置类

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值