Spring框架中使用注解

来源:互联网 发布:网络教学有什么特点 编辑:程序博客网 时间:2024/06/06 07:31

在Spring框架中,我们通过在配置文件中配置bean属性为对象进行注入。

我们创建一个项目回顾一下:

一、新建一个项目TestSpring7,使用MyEclipse赋予Spring能力


二、新建一个dao类

package demo.dao;public class PersonDao {public void add(){System.out.println("执行了PersonDao的add方法");}}
三、新建一个service类

package demo.service;import demo.dao.PersonDao;public class PersonService {private PersonDao dao;public void setDao(PersonDao dao) {this.dao = dao;}public void run(){dao.add();}}
四、在配置文件中配置bean

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"><bean name="personService" class="demo.service.PersonService"><property name="dao" ref="personDao"></property></bean><bean  name="personDao" class="demo.dao.PersonDao"></bean></beans>
五、新建一个test类进行测试

package demo.test;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import demo.service.AnimalService;import demo.service.PersonService;import demo.service.impl.AnimalServiceImpl;import demo.service.impl.PersonServiceImpl;public class SpringTest {@Testpublic void test(){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");PersonService service = (PersonService) context.getBean("personService");service.run();}}

console显示如下:


上面就是通过配置文件注入bean的,还有一种方式,就是使用注解

Spring的注解有两种方式实现,一种是使用Spring自带的的 @Autowired注释,在默认情况下使用 @Autowired注释进行自动注入时,Spring 容器中匹配的候选 Bean 数目必须有且仅有一个。当找不到一个匹配的 Bean 时,Spring 容器将抛出BeanCreationException异常,并指出必须至少拥有一个匹配的 Bean。我们来实现一下。

一、修改service类,在dao属性前加上@Autowired

package demo.service;import org.springframework.beans.factory.annotation.Autowired;import demo.dao.PersonDao;public class PersonService {@Autowiredprivate PersonDao dao;public void setDao(PersonDao dao) {this.dao = dao;}public void run(){dao.add();}}
二、修改配置文件

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"><!-- 该BeanPostProcessor将自动起作用,对标注 @Autowired的 Bean 进行自动注入 --><bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/><bean name="personService" class="demo.service.PersonService"></bean><bean  name="personDao" class="demo.dao.PersonDao"></bean></beans>
把name为personService的bean中的属性删除(因为使用了注解,不用配置),配置文件中还配置了一个bean,Spring通过一个BeanPostProcessor对@Autowired进行解析,所以要让@Autowired起作用必须事先在Spring容器中声明AutowiredAnnotationBeanPostProcessorBean。

三、测试,结果如下:



Spring 不但支持自己定义的 @Autowired的注释,还支持几个由 JSR-250 规范定义的注释,它们分别是 @Resource、@PostConstruct以及 @PreDestroy。(建议使用这种注解注入,国际标准)

@Resource 的作用相当于 @Autowired,只不过 @Autowired按byType自动注入,而@Resource 默认按byName自动注入罢了。@Resource 有两个属性是比较重要的,分别是 name 和 type,Spring 将@Resource 注释的 name 属性解析为 Bean 的名字,而 type 属性则解析为 Bean 的类型。当找不到与名称匹配的bean则按照类型来装配注入。我们来实现一下。

一、修改service类,在dao属性前加上@Resource

public class PersonService {@Resourceprivate PersonDao dao;public void run(){dao.add();}}
二、修改配置文件(修改了头部,添加了支持Resource注解)

<?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:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"><!-- 将隐式地向 Spring 容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor以及equiredAnnotationBeanPostProcessor这 4 个BeanPostProcessor。 --><context:annotation-config /><bean name="personService" class="demo.service.PersonService"></bean><bean  name="personDao" class="demo.dao.PersonDao"></bean></beans>
三、运行测试类,执行成功



它的执行过程是这样的,@Resouce因为没有配置name和type属性,它会自动使用它注解的属性名去配置文件中找与这个属性名相同的bean,找不到的情况下会根据类型type去找。本例执行中找不到名为dao的bean,注解最终根据type去完成dao的注入。

我们可以这样使用:

@Resouce(name=“personDao”)代替@Resouce,这样,注解根据name查找到bean完成dao的注入;@Resource(type=PersonDao.class)代替@Resouce,这样,注解根据type查找到bean完成dao的注入。

在之前我们是通过<bean>元素的init-method/destroy-method 属性指定初始化之后 / 销毁之前调用的操作方法,现在用注解实现。两个注释分别是 @PostConstruct和 @PreDestroy,第一个的作用是在初始化bean对象后执行注释方法,第二个的作用是在bean销毁前执行注释方法。我们使用一下:

修改service类:

package demo.service;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;import javax.annotation.Resource;import demo.dao.PersonDao;public class PersonService {@Resource(type=PersonDao.class)private PersonDao dao;public void run(){dao.add();}@PostConstructpublic void init(){System.out.println("执行了init方法");}@PreDestroypublic void destroy(){System.out.println("执行了destroy方法");}}

修改测试类:

package demo.test;import org.junit.Test;import org.springframework.context.support.ClassPathXmlApplicationContext;import demo.service.PersonService;public class SpringTest {@Testpublic void test(){ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");PersonService service = (PersonService) context.getBean("personService");service.run();context.close();}}

运行结果:


再了解一下其它的注释: @Component(不推荐使用)、@repository 、@Service 、@Controller 

这些注解是用在类上面的。

@component 是所有受Spring 管理组件的通用形式,Spring还提供了更加细化的注解形式:@repository、@Service 、@Controller,它们分别对应持久化层Bean ,业务层Bean ,和控制层Bean 。这些注解与@component 的语义是一样的,完全通用。我们使用一下它们:

一、新建一个配置文件bean.xml

<?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:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">        <!-- 有了<context:component-scan>,<context:annotation-config/>标签可以移除掉,它会自动扫描包demo,为每个注释的类自动配置注入,所有不用再配置bean了--><context:component-scan base-package="demo"/></beans>


二、添加注解

dao类

package demo.dao;import org.springframework.stereotype.Repository;//注册了一个bean,默认名字是personDao@Repositorypublic class PersonDao {public void add(){System.out.println("执行了PersonDao的add方法");}}

service类

package demo.service;import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;import javax.annotation.Resource;import org.springframework.stereotype.Service;import demo.dao.PersonDao;//注册了一个bean,默认名字是personService@Servicepublic class PersonService {@Resource(name="personDao")private PersonDao dao;public void run(){dao.add();}@PostConstructpublic void init(){System.out.println("执行了init方法");}@PreDestroypublic void destroy(){System.out.println("执行了destroy方法");}}
action类

package demo.acton;import javax.annotation.Resource;import org.springframework.stereotype.Controller;import demo.service.PersonService;//注册了一个bean,默认名字是personAction@Controllerpublic class PersonAction {@Resource(name="personService")private PersonService service;public void go(){service.run();}}

测试:

@Testpublic void test2(){ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");PersonAction action = (PersonAction) context.getBean("personAction");action.go();context.close();}

运行结果



Spring框架中使用注解差不多就这些内容了,接下来就是在实际项目中实现了,简化我们的配置。

0 0
原创粉丝点击