`
IT阿狸
  • 浏览: 67153 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Spring的注解,带一小例子

阅读更多

这里使用Spring3.0+Hibernate3.3作为例子。

例子中的实体类也是用的Hibernate注解里的实体(上一篇Blog)

 

一、Spring的一些常用注解

1.@Autowired注解(不推荐使用,建议使用@Resource)

@Autowired可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。@Autowired的标注位置不同,它们都会在Spring在初始化这个bean时,自动装配这个属性。

 

2.@Resource注解 

JSR-250标准注解,推荐使用它来代替Spring专有的@Autowired注解。@Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按byName自动注入罢了。@Resource有两个属性是比较重要的,分别是name和type,Spring将 @Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。

@Resource装配顺序:

a.如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常

b.如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常

c.如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常

d.如果既没有指定name,又没有指定type,则自动按照byName方式进行装配(见2);如果没有匹配,则回退为一个原始类型(UserDao)进行匹配,如果匹配则自动装配

 

3.@Component注解 (不推荐使用)

只需要在对应的类上加上一个@Component注解,就将该类定义为一个Bean了。Spring还提供了更加细化的注解形式:@Repository、@Service、@Controller,它们分别对应存储层Bean,业务层Bean,和展示层Bean。这些注解与@Component的语义是一样的,完全通用,在Spring以后的版本中可能会给它们追加更多的语义。所以,我们推荐使用@Repository、@Service、@Controller来替@Component。

 

二、Spring3.0的头部文件

<?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:tx="http://www.springframework.org/schema/tx"  
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="  
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
            http://www.springframework.org/schema/context  
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	
</beans>

 

 

三、dao和daoImpl

dao:

package org.e276.dao;

import java.util.List;
import org.e276.entity.Employee;

/**
 * 接口
 * 
 * @author miao
 * 
 */
public interface EmployeeDao {

	/**
	 * 根据id查询员工
	 * 
	 * @param id
	 * @return
	 */
	public Employee findEmployeeById(Integer id);

	/**
	 * 删除多个员工
	 * 
	 * @param ids
	 * @return
	 */
	public int deleteEmployees(Integer... ids);

	/**
	 * 查询所有的工资,并按升序排序
	 * 
	 * @return
	 */
	public List<Employee> findAllEmployees();

	/**
	 * 查询所有大于平均工资的员工信息
	 * 
	 * @return
	 */
	public List<Employee> findEmployeeGtAvgSalary();

}

 

 

daoImpl:

package org.e276.dao.impl;

import java.sql.SQLException;
import java.util.List;
import org.e276.dao.EmployeeDao;
import org.e276.entity.Employee;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

/**
 * 接口实现类
 * 
 * @author miao
 * 
 */
@Repository("employeeDao")
public class EmployeeDaoImpl extends HibernateDaoSupport implements EmployeeDao {

	/**
	 * 注入会话工厂,方法名字在可以随便起,给Spring用来注入
	 */
	@Autowired
	public void injectSessionFactory(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

	@Override
	public Employee findEmployeeById(Integer id) {
		return super.getHibernateTemplate().get(Employee.class, id);
	}

	@Override
	public int deleteEmployees(Integer... ids) {
		int count = 0;
		for (Integer id : ids) {
			super.getHibernateTemplate().bulkUpdate("delete from Employee where id=?", id);
			count++;
		}
		return count;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Employee> findAllEmployees() {
		DetachedCriteria criteria = DetachedCriteria.forClass(Employee.class);
		criteria.addOrder((Order.asc("salary")));
		return super.getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public List<Employee> findEmployeeGtAvgSalary() {
		return (List<Employee>) super.getHibernateTemplate().execute(new HibernateCallback() {
			String sql = "select id, name, sex, salary, birthday, depart_id from employee where salary>(select avg(salary) from employee)";

			@Override
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Query query = session.createSQLQuery(sql).addEntity(Employee.class);
				return query.list();
			}
		});
	}

}

 

 

四、biz和bizImpl

biz:

package org.e276.biz;

import java.util.List;
import org.e276.entity.Employee;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业务接口
 * 
 * @author miao
 * 
 */
public interface EmployeeBiz {

	/**
	 * 根据id查询员工
	 * 
	 * @param id
	 * @return
	 */
	public Employee findEmployeeById(Integer id);

	/**
	 * 删除多个员工,支持注解事务
	 * 
	 * @param ids
	 * @return
	 */
	@Transactional
	public int deleteEmployees(Integer... ids);
	
	/**
	 * 查询所有的工资,并按升序排序
	 * @return
	 */
	public List<Employee> findAllEmployees();
	
	/**
	 * 查询所有大于平均工资的员工信息
	 * @return
	 */
	public List<Employee> findEmployeeGtAvgSalary();
	
}

 

 

bizImpl:

package org.e276.biz.impl;

import java.util.List;
import org.e276.biz.EmployeeBiz;
import org.e276.dao.EmployeeDao;
import org.e276.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 业务接口实现类
 * @author miao
 *
 */
@Service("employeeBiz")
public class EmployeeBizImpl implements EmployeeBiz {

	//无需set方法
	@Autowired
	private EmployeeDao employeeDao;

	@Override
	public Employee findEmployeeById(Integer id) {
		return employeeDao.findEmployeeById(id);
	}

	@Override
	public int deleteEmployees(Integer... ids) {
		return employeeDao.deleteEmployees(ids);
	}

	@Override
	public List<Employee> findAllEmployees() {
		return employeeDao.findAllEmployees();
	}

	@Override
	public List<Employee> findEmployeeGtAvgSalary() {
		return employeeDao.findEmployeeGtAvgSalary();
	}
	
}

 

 

五、Spring的配置文件

<?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:tx="http://www.springframework.org/schema/tx"  
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="  
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
            http://www.springframework.org/schema/context  
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- 哪个包里面的类由Spring管理 -->
	<context:component-scan base-package="org.e276" />
	<!-- 表示隐式的向Spring容器注册 -->
	<context:annotation-config />
	
	<!-- 会话工厂 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="configLocation" value="file:src/hibernate.cfg.xml">
		</property>
	</bean>
	
	<!-- 事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory">
			<ref bean="sessionFactory" />
		</property>
	</bean>
	
	<!-- 有关注解式事务的配置 -->
	<tx:annotation-driven transaction-manager="transactionManager" />
	
</beans>

 

 

六、测试类

package org.e276.test;

import java.util.List;
import org.e276.biz.EmployeeBiz;
import org.e276.entity.Employee;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 测试类
 * 
 * @author miao
 * 
 */
public class SpringEmployee {

	static ApplicationContext context;
	EmployeeBiz employeeBiz;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		context = new ClassPathXmlApplicationContext("applicationContext.xml");
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		context = null;
	}

	@Before
	public void setUp() throws Exception {
		employeeBiz = context.getBean("employeeBiz", EmployeeBiz.class);
	}

	@After
	public void tearDown() throws Exception {
		employeeBiz = null;
	}

	/**
	 * 根据id查询员工
	 */
	public void findEmployeeById() {
		Employee employee = employeeBiz.findEmployeeById(1000);
		System.out.println(employee);
	}

	/**
	 * 删除多条记录 删除编号50,100,150的员工
	 */
	public void deleteEmployees() {
		int row = employeeBiz.deleteEmployees(50, 100, 150);
		System.out.println("共" + row + "条记录被删除!");
	}

	/**
	 * 查询所有的员工,并按工资升序排序
	 */
	public void findAllEmployees() {
		List<Employee> list = employeeBiz.findAllEmployees();
		for (Employee employee : list) {
			System.out.println(employee);
		}
	}

	/**
	 * 查询所有大于平均工资的员工信息
	 */
	@Test
	public void findEmployeeGtAvgSalary() {
		List<Employee> list = employeeBiz.findEmployeeGtAvgSalary();
		for (Employee employee : list) {
			System.out.println(employee);
		}
	}
}

 

 

七、demo

E276-Annotation.zip

分享到:
评论

相关推荐

    Spring 注解 小例子

    这个小例子将深入探讨Spring框架中的主要注解及其用法。 1. `@Component`、`@Service`、`@Repository` 和 `@Controller` 这些注解是Spring组件扫描的基础,它们定义了一个bean。`@Component`是最通用的,适用于...

    hibernate+spring注解例子

    这个"hibernate+spring注解例子"项目提供了一个实际的登录场景,帮助学习者更好地理解和运用这两个框架的注解特性。通过深入学习和实践,开发者能够提高开发效率,降低出错概率,为构建高效、稳定的Java应用程序打下...

    spring注解 -----最简单的注解与自动装配例子

    总的来说,Spring注解极大地简化了Spring应用的配置,使得开发者可以更加专注于业务逻辑,而不是繁琐的XML配置。通过合理使用@Autowired、@ComponentScan等注解,我们可以构建出松散耦合、易于维护的系统。在实践中...

    SSH注解方式整合小例子

    在这个“SSH注解方式整合小例子”中,我们将深入探讨如何使用注解来简化SSH框架的配置过程,使得开发更加便捷。 **Struts2** 是一个基于MVC设计模式的Action驱动的Web应用框架,它通过注解可以实现Action类的声明式...

    struts2+mybatis+spring 注解很好的例子

    在这个"struts2+mybatis+spring 注解很好的例子"中,开发者可能已经展示了如何在Struts2的Action类中使用Spring的注解来注入Service,然后在Service中利用MyBatis的注解进行数据库操作。整个流程可能包含以下步骤: ...

    spring aop 注解例子

    **Spring AOP 注解例子详解** 在 Spring 框架中,面向切面编程(Aspect Oriented Programming,AOP)是一种强大的设计模式,它允许我们分离关注点,将业务逻辑与系统服务(如日志、事务管理等)解耦。在 Spring AOP...

    spring2.5基于注解例子程序

    Spring 2.5引入了自动扫描功能,通过`@ComponentScan`注解,Spring容器可以自动发现并注册带有特定注解的类,无需在XML中显式声明。这极大地方便了项目的构建和维护。 3. **基于注解的事务管理**: `@...

    spring注解方式解析

    在上面的例子中,`@Service`注解标记了UserService是一个业务层组件,而`@Autowired`注解告诉Spring容器自动寻找与userRepository类型匹配的bean进行注入。Spring会通过类型匹配、名称匹配或者使用@Qualifier注解...

    spring注解实例

    本文将深入探讨Spring注解注入的相关知识点,以及如何通过提供的压缩包文件进行实践学习。 **1. Spring注解概述** 在Spring框架中,注解提供了元数据的方式来配置bean,使得我们不再需要XML配置文件。常见的注解...

    基于SPRING的一个小例子

    总之,这个基于Spring的小例子会涵盖Spring的基本概念和核心特性,如依赖注入、面向切面编程、IoC容器、注解驱动的配置以及Spring MVC。通过学习和实践,你可以逐步理解Spring如何帮助我们构建更高效、更易于维护的...

    spring mvc 注解例子

    Spring MVC 是一个强大的Java Web开发框架,用于...在提供的链接文章"spring mvc 注解实现"中,你应该能发现更多关于如何实际应用这些注解的例子和详细解释。学习和理解这些注解对于提升Spring MVC的开发效率至关重要。

    我的博客spring注解概述的示例代码

    在这个"我的博客spring注解概述的示例代码"资源中,我们可能找到如何使用`@Autowired`来自动装配bean的实例。 首先,让我们了解什么是依赖注入。在面向对象编程中,一个类往往依赖于其他类来完成特定任务。依赖注入...

    spring注解完整版[定义].pdf

    在配置文件中,通过添加和元素,Spring会扫描指定的包(或所有包,如果使用"*"),查找带有特定注解(如@Service、@Component、@Repository、@Controller等)的类,并自动处理它们。这使得我们无需在XML中为每个bean...

    s2sh+springSecurity的注解配置例子

    标题 "s2sh+springSecurity的注解配置例子" 提供了一个关于整合Spring Security与Struts 2(S2)和Hibernate(SH)框架的注解配置实践的线索。这通常涉及到在Java web应用程序中创建一个安全的环境,通过利用Spring ...

    spring MVC 注解的使用例子

    Spring MVC 是一个基于Java的轻量级Web应用框架,它为构建RESTful应用程序提供了强大的支持。在本示例中,我们将深入探讨如何使用Spring MVC中的...学习和实践这个例子将有助于你掌握Spring MVC的注解驱动开发方式。

    SPRING学习小例子

    《Spring学习小例子详解》 在Java开发领域,Spring框架无疑是使用最为广泛的轻量级框架之一,它提供了全面的的企业级应用开发解决方案。本篇将深入解析“SPRING学习小例子”,涵盖Spring的核心特性——依赖注入(DI...

    java入门级spring加maven的小例子

    在这个入门级的小例子中,我们将通过结合Maven来快速搭建一个Spring项目,帮助初学者理解Spring与Maven的基本用法。 首先,Maven是一个项目管理工具,它管理项目的构建、报告和依赖关系,通过一个配置文件pom.xml,...

    spring注解Quartz定时执行功能

    下面我们将深入探讨如何利用Spring注解实现Quartz定时执行功能。 首先,我们需要引入Quartz和Spring的相关依赖。在Maven的pom.xml文件中添加以下依赖: ```xml &lt;groupId&gt;org.quartz-scheduler &lt;artifactId&gt;...

    ssh框架构建 hibernate注解 spring注解

    Spring注解如`@Component`、`@Service`、`@Repository`和`@Controller`用于标记bean,使得Spring容器能够自动检测和管理这些bean。此外,`@Autowired`注解用于自动装配bean的依赖,而`@Transactional`注解则可以声明...

Global site tag (gtag.js) - Google Analytics