spring注解实例1

来源:互联网 发布:凤凰财经数据库 编辑:程序博客网 时间:2024/05/17 06:49

随着jdk1.5引进注解功能后,使得注解越来越流行开来,各个开源框架纷纷提供了对注解的支持,其中Spring从3.0版本以后便提供了较为全面的注解支持,对于Spring大行其道的今天,掌握新技术对于自身成长来说是非常有利的。今天笔者就此总结分享给大家。

一、IOC容器

IOC是Spring的核心技术,以前一直都是以XML的方式来配置的,现在能利用注解简化配置的方式。实例如下:

action层:

[java] view plaincopy
  1. package com.action;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.context.annotation.Scope;  
  6. import org.springframework.stereotype.Controller;  
  7.   
  8. import com.entity.Student;  
  9. import com.opensymphony.xwork2.ActionSupport;  
  10. import com.service.IStudentService;  
  11.   
  12. @Controller("StudentAction")  
  13. @Scope("prototype")  
  14. public class StudentAction extends ActionSupport {  
  15.   
  16.     private static final long serialVersionUID = -1523904052147405750L;  
  17.   
  18.     private Student student;  
  19.       
  20.     @Resource(name="studentService2")  
  21.     private IStudentService studentService;  
  22.   
  23.     @Override  
  24.     public String execute() throws Exception {  
  25.         String id = studentService.insert(student);  
  26.         System.out.println(id);  
  27.         return "success";  
  28.     }  
  29.       
  30.     public Student getStudent() {  
  31.         return student;  
  32.     }  
  33.   
  34.     public void setStudent(Student student) {  
  35.         this.student = student;  
  36.     }  
  37. }  

service层:

[java] view plaincopy
  1. package com.service.impl;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Service;  
  6.   
  7. import com.dao.IStudentDao;  
  8. import com.entity.Student;  
  9. import com.service.IStudentService;  
  10.   
  11. @Service  
  12. public class StudentService implements IStudentService {  
  13.   
  14.     @Resource  
  15.     private IStudentDao studentDao;  
  16.   
  17.     @Override  
  18.     public String insert(Student student) {  
  19.         String id = studentDao.insert(student);  
  20.         return id;  
  21.     }  
  22. }  

dao层:

[java] view plaincopy
  1. package com.dao.jdbc.impl;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;  
  6. import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport;  
  7. import org.springframework.jdbc.core.namedparam.SqlParameterSource;  
  8. import org.springframework.jdbc.support.GeneratedKeyHolder;  
  9. import org.springframework.jdbc.support.KeyHolder;  
  10. import org.springframework.stereotype.Repository;  
  11.   
  12. import com.dao.IStudentDao;  
  13. import com.util.SQLUtils;  
  14. import com.util.SqlType;  
  15.   
  16.   
  17. @Repository  
  18. public class StudentDao implements IStudentDao {  
  19.   
  20.     @Resource  
  21.     private NamedParameterJdbcDaoSupport namedParameterJdbcDaoSupport;  
  22.   
  23.     @Override  
  24.     public <T> String insert(T t) {  
  25.         String sql = SQLUtils.getSql(t.getClass(), SqlType.INSERT);  
  26.         KeyHolder keyHolder = new GeneratedKeyHolder();  
  27.         SqlParameterSource paramSource = new BeanPropertySqlParameterSource(t);  
  28.         namedParameterJdbcDaoSupport.getNamedParameterJdbcTemplate().update(sql, paramSource, keyHolder, new String[] { "id" });  
  29.         return keyHolder.getKeys().get("id").toString();  
  30.     }  
  31. }  

struts.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.3.dtd">  
  5.   
  6. <struts>  
  7.     <constant name="struts.objectFactory" value="spring" />  
  8.   
  9.     <package name="struts" namespace="" extends="struts-default">  
  10.         <action name="student" class="StudentAction">  
  11.             <result name="success">/success.jsp</result>  
  12.         </action>  
  13.     </package>  
  14. </struts>  

applicationContext.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xmlns:tx="http://www.springframework.org/schema/tx"  
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
  8.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd  
  9.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  10.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">  
  11.   
  12.     <context:annotation-config />  
  13.   
  14.     <context:component-scan base-package="com.action,com.dao,com.service,com.servlet" />  
  15.   
  16.     <aop:aspectj-autoproxy />  
  17.       
  18.     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  19.         <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
  20.         <property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />  
  21.         <property name="username" value="wang" />  
  22.         <property name="password" value="wang" />  
  23.     </bean>  
  24.       
  25.     <bean id="namedParameterJdbcDaoSupport" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport">  
  26.         <property name="dataSource" ref="dataSource" />  
  27.     </bean>  
  28.   
  29.     <bean id="jdbcTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  30.         <property name="dataSource" ref="dataSource" />  
  31.     </bean>  
  32.       
  33.     <aop:config>  
  34.         <aop:pointcut id="allManagerMethod" expression="execution(* com.dao.*.*(..))"/>  
  35.         <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod"/>  
  36.     </aop:config>  
  37.   
  38.     <tx:advice id="txAdvice" transaction-manager="jdbcTransactionManager">  
  39.         <tx:attributes>  
  40.             <tx:method name="insert*"/>  
  41.             <tx:method name="save*"/>  
  42.             <tx:method name="update*"/>  
  43.             <tx:method name="delete*"/>  
  44.             <tx:method name="find*" read-only="true"/>  
  45.             <tx:method name="*" read-only="true"/>  
  46.         </tx:attributes>  
  47.     </tx:advice>  
  48. </beans>  

web.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
  3.   <display-name>sshAnotation</display-name>  
  4.     
  5.   <context-param>  
  6.     <param-name>contextConfigLocation</param-name>  
  7.     <param-value>classpath:com/config/applicationContext.xml</param-value>  
  8.   </context-param>  
  9.     
  10.   <filter>  
  11.     <filter-name>struts</filter-name>  
  12.     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  13.     <init-param>  
  14.         <param-name>config</param-name>  
  15.         <param-value>struts-default.xml,struts-plugin.xml,/com/config/struts.xml</param-value>  
  16.     </init-param>  
  17.   </filter>  
  18.     
  19.   <filter-mapping>  
  20.     <filter-name>struts</filter-name>  
  21.     <url-pattern>/*</url-pattern>  
  22.   </filter-mapping>  
  23.     
  24.   <listener>  
  25.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  26.   </listener>  
  27.     
  28.   <welcome-file-list>  
  29.     <welcome-file>index.jsp</welcome-file>  
  30.     <welcome-file>default.jsp</welcome-file>  
  31.   </welcome-file-list>  
  32. </web-app>  

通过以上实例我们可以观察出,applicationContext.xml配置文件中已经没有以前配置的业务bean(如studentDao)了,取而代之的是写在代码里的@Controller、@Service、@Repository和@Resource,那么他们各代表什么意义呢?

@Controller、@Service、@Repository是在@Component基础上拓展而来,它们分别对应表现层Bean,业务层Bean ,和数据层Bean,他们除了语义上不同之外,本质和用法上没有什么区别,。而@Component以过时不推荐使用。

@Resource其实与@Autowired的作用相似,都是代替<property>标签来注入对象的,但推荐使用@Resource。

@Scope是用来设定Bean的生命周期的。

除了上述常用的之外,其他的还有@Lazy、@DependsOn、@PostConstruct、@PreDestroy等其他的注解,作用分别是:延迟初始化、依赖其他Bea、初始化方法、析构方法。

注解@标识放置的代码位置不是随意的,根据jdk1.5规范,要求注解写在类、接口、属性(成员变量)、方法、构造函数或方法参数上。不同的注解,可放置的位置也不同。例如上述:@Controller、@Service、@Repository、@Scope、@Lazy、@DependsOn都只能放在类上;@Resource、@Autowired能放在属性、方法、构造函数上;@PostConstruct、@PreDestroy则只能放在方法上

要想使用Spring注解,必须要在applicationContext.xml中配置<context:annotation-config>和<context:component-scan>这两个标签,前者用来告诉Spring要启用注解,后者则用来告诉Spring注解所在的包,以便Spring启动时扫描包并进行注入。

其实自Spring3.0以后IOC的Bean常用XML配置方式基本都有对应的注解方式,只不过另外的都不太常用,笔者了解的也不多,所以就不叙述了。

那么在这基础之上,我再为大家扩充点:1,、项目层次多于三层。2、一个接口多个实现类

1、项目层次多于三层

我们知道Spring就主流三层架构给出了@Controller、@Service、@Repository来对应,但如果项目中是多层(如action、servlet、service、dao)怎么办呢?其实@Service并不仅仅就局限于一层,我们可以在service层上用,同样可以在servlet层上用,例如:

servlet层:

[java] view plaincopy
  1. package com.servlet.impl;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Service;  
  6.   
  7. import com.entity.Student;  
  8. import com.service.IStudentService;  
  9. import com.servlet.IStudentServlet;  
  10.   
  11. @Service  
  12. public class StudentServlet implements IStudentServlet {  
  13.   
  14.     @Resource  
  15.     private IStudentService studentService;  
  16.       
  17.     @Override  
  18.     public String insert(Student student) {  
  19.         return studentService.insert(student);  
  20.     }  
  21. }  

action层中只需将原先IStudentService的属性改为IStudentSerlet即可。

2、一个接口多个实现类

其实每个注解都是有参数可以指定的【如实例中:@Controller("StudentAction")】,如果不指定参数【即@Controller】,Spring默认则根据命名的名称来查找注入。如果指定了则根据的参数进行注入。一个接口有多个实现类,我们则可以通过@Resource(name="studentService2")来区分。

 

好了,本篇博文就IOC的注解方式进行了讲解,下一篇我们会继续介绍AOP和事务的注解方式。

0 0