spring学习笔记 -- day14 基于注解的整合

一、基于注解整合要明确

1、注解整合仍然使用上面的环境,就是把xml的配置全部换成注解

2、spring的注解整合有两种方式,一种是用xml文件,一种是纯注解。

3、hibernate注解整合是把实体类映射改为JPA注解映射

二、spring的配置使用注解实现

1、配置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: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/tx 
       					   http://www.springframework.org/schema/tx/spring-tx.xsd
        				   http://www.springframework.org/schema/aop 
        				   http://www.springframework.org/schema/aop/spring-aop.xsd
        				   http://www.springframework.org/schema/context 
        				   http://www.springframework.org/schema/context/spring-context.xsd"> 
	<!-- 配置spring在创建容器时要扫描的包 -->
	<context:component-scan base-package="cn.itcast"></context:component-scan>
</beans>

2、配置spring的事务管理器、jdbc连接配置

<?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: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/tx 
       					   http://www.springframework.org/schema/tx/spring-tx.xsd
        				   http://www.springframework.org/schema/aop 
        				   http://www.springframework.org/schema/aop/spring-aop.xsd
        				   http://www.springframework.org/schema/context 
        				   http://www.springframework.org/schema/context/spring-context.xsd"> 
	<!-- 配置spring在创建容器时要扫描的包 -->
	<context:component-scan base-package="cn.itcast"></context:component-scan>
	
	<!-- 开启spring对注解事务的支持 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	<!-- 配置事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<!-- 配置HibernateTemplate -->
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<!-- 配置一个SessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<!-- 1.连接数据库的信息 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 2.hibernate的基本配置 -->
		<property name="hibernateProperties">
			<props>
				<!-- 数据库的方言 -->
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<!-- 是否显示SQL语句 -->
				<prop key="hibernate.show_sql">true</prop>
				<!-- 是否格式化SQL语句 -->
				<prop key="hibernate.format_sql">false</prop>
				<!-- 选择生成DDL语句的策略 -->
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<!-- 把session绑定到当前线程上   -->
				<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>
			</props>
		</property>
		<!-- 3.映射文件的位置 -->
		<property name="mappingLocations">  
            <array>  
                <value>classpath:cn/itcast/domain/*.hbm.xml</value>  
            </array>  
        </property>  
	</bean>
	
	<!-- 配置数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/crm_ee247"></property>
		<property name="user" value="root"></property>
		<property name="password" value="1234"></property>
	</bean>
</beans>

3、编写dao实现类代码

package cn.itcast.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import cn.itcast.dao.ICustomerDao;
import cn.itcast.domain.Customer;
/**
 * 客户的持久层实现类
 * @author wingzhe
 *  此类可以用于基于XML和基于注解的配置。因为在类中有独立的HibernateTemplate定义
 *  但是如果用于基于xml的配置从第17行代码到第21行代码都是重复的
 */
@Repository("customerDao")
public class CustomerDaoImpl implements ICustomerDao {

	@Autowired
	private HibernateTemplate hibernateTemplate;

	@Override
	public void saveCustomer(Customer customer) {
		hibernateTemplate.save(customer);

	}

	@Override
	public List<Customer> findAllCustomer() {
		return (List<Customer>) hibernateTemplate.find("from Customer");
	}

}

4、编写service层实现类

package cn.itcast.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.dao.ICustomerDao;
import cn.itcast.domain.Customer;
import cn.itcast.service.ICustomerService;
/**
 * 客户的业务层实现类
 * @author wingzhe
 *
 */
@Service("customerService")
@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
public class CustomerServiceImpl implements ICustomerService {

	@Autowired
	private ICustomerDao customerDao;
	

	@Override
	public void saveCustomer(Customer customer) {
		customerDao.saveCustomer(customer);
	}

	@Override
	@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
	public List<Customer> findAllCustomer() {
		return customerDao.findAllCustomer();
	}

}

5、编写动作类

package cn.itcast.web.action;

import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.domain.Customer;
import cn.itcast.service.ICustomerService;
/**
 * Customer的动作类
 * @author wingzhe
 *
 */
@Controller("customerAction")
@Scope("prototype")
public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {

	private Customer customer = new Customer();

	@Autowired
	private ICustomerService customerService;

	@Override
	public Customer getModel() {
		return customer;
	}
	
	/**
	 * 保存客户 
	 * @return
	 */
	public String addCustomer(){
		customerService.saveCustomer(customer);
		return "addCustomer";
	}
	
	
	/**
	 * 查询所有客户
	 * @return
	 */
	private List<Customer> customers;	
	
	public String findAllCustomer(){
		customers = customerService.findAllCustomer();
		return "findAllCustomer";
	}
	
	/**
	 * 获取添加客户页面
	 * @return
	 */
	public String addUICustomer(){
		return "addUICustomer";
	}

	
	
	public List<Customer> getCustomers() {
		return customers;
	}
	public void setCustomers(List<Customer> customers) {
		this.customers = customers;
	}
}

三、hibernate映射使用注解配置实现

1、编写javaBean

package cn.itcast.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
 * 客户的实体类
 * @author wingzhe
 * javax.persistence包下的注解
 * JPA规范
 */
@Entity
@Table(name="cst_customer")
public class Customer implements Serializable {
	
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="cust_id")
	private Long custId;
	
	@Column(name="cust_name")
	private String custName;
	
	@Column(name="cust_source")
	private String custSource;
	
	@Column(name="cust_industry")
	private String custIndustry;
	
	@Column(name="cust_level")
	private String custLevel;
	
	@Column(name="cust_address")
	private String custAddress;
	
	@Column(name="cust_phone")
	private String custPhone;
	
	
	public Long getCustId() {
		return custId;
	}
	public void setCustId(Long custId) {
		this.custId = custId;
	}
	public String getCustName() {
		return custName;
	}
	public void setCustName(String custName) {
		this.custName = custName;
	}
	public String getCustSource() {
		return custSource;
	}
	public void setCustSource(String custSource) {
		this.custSource = custSource;
	}
	public String getCustIndustry() {
		return custIndustry;
	}
	public void setCustIndustry(String custIndustry) {
		this.custIndustry = custIndustry;
	}
	public String getCustLevel() {
		return custLevel;
	}
	public void setCustLevel(String custLevel) {
		this.custLevel = custLevel;
	}
	public String getCustAddress() {
		return custAddress;
	}
	public void setCustAddress(String custAddress) {
		this.custAddress = custAddress;
	}
	public String getCustPhone() {
		return custPhone;
	}
	public void setCustPhone(String custPhone) {
		this.custPhone = custPhone;
	}
	@Override
	public String toString() {
		return "Customer [custId=" + custId + ", custName=" + custName + ", custSource=" + custSource
				+ ", custIndustry=" + custIndustry + ", custLevel=" + custLevel + ", custAddress=" + custAddress
				+ ", custPhone=" + custPhone + "]";
	}
	
	
}

2、在spring配置文件中指定使用JPA的javaBean位置

<?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: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/tx 
       					   http://www.springframework.org/schema/tx/spring-tx.xsd
        				   http://www.springframework.org/schema/aop 
        				   http://www.springframework.org/schema/aop/spring-aop.xsd
        				   http://www.springframework.org/schema/context 
        				   http://www.springframework.org/schema/context/spring-context.xsd"> 
	<!-- 配置spring在创建容器时要扫描的包 -->
	<context:component-scan base-package="cn.itcast"></context:component-scan>
	
	<!-- 开启spring对注解事务的支持 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
	
	<!-- 配置事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<!-- 配置HibernateTemplate -->
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<!-- 配置一个SessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<!-- 1.连接数据库的信息 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 2.hibernate的基本配置 -->
		<property name="hibernateProperties">
			<props>
				<!-- 数据库的方言 -->
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<!-- 是否显示SQL语句 -->
				<prop key="hibernate.show_sql">true</prop>
				<!-- 是否格式化SQL语句 -->
				<prop key="hibernate.format_sql">false</prop>
				<!-- 选择生成DDL语句的策略 -->
				<prop key="hibernate.hbm2ddl.auto">update</prop>
				<!-- 把session绑定到当前线程上   -->
				<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>
			</props>
		</property>
		<!-- 3.映射文件的位置 -->
		<property name="packagesToScan">
			<array>
				<value>cn.itcast.domain</value>
			</array>
		</property>
	</bean>
	
	<!-- 配置数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/crm_ee247"></property>
		<property name="user" value="root"></property>
		<property name="password" value="1234"></property>
	</bean>
</beans>

四、struts2的配置使用注解实现

1、拷贝struts2注解的jar包


2、编写动作类

package cn.itcast.web.action;

import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.domain.Customer;
import cn.itcast.service.ICustomerService;
/**
 * Customer的动作类
 * @author zhy
 *
 */
@Controller("customerAction")
@Scope("prototype")
@ParentPackage("struts-default")
@Namespace("/customer")
public class CustomerAction extends ActionSupport implements ModelDriven<Customer> {

	private Customer customer = new Customer();

	@Autowired
	private ICustomerService customerService;

	@Override
	public Customer getModel() {
		return customer;
	}
	
	/**
	 * 保存客户 
	 * @return
	 */
	@Action(value="addCustomer",results={
			@Result(name="addCustomer",type="redirect",location="/jsp/success.jsp")
	})
	public String addCustomer(){
		customerService.saveCustomer(customer);
		return "addCustomer";
	}
	
	
	/**
	 * 查询所有客户
	 * @return
	 */
	private List<Customer> customers;	
	
	@Action(value="findAllCustomer",results={
			@Result(name="findAllCustomer",type="dispatcher",location="/jsp/customer/list.jsp")
	})
	public String findAllCustomer(){
		customers = customerService.findAllCustomer();
		return "findAllCustomer";
	}
	
	/**
	 * 获取添加客户页面
	 * @return
	 */
	@Action(value="addUICustomer",results={
			@Result(name="addUICustomer",type="dispatcher",location="/jsp/customer/add.jsp")
	})
	public String addUICustomer(){
		return "addUICustomer";
	}

	
	
	public List<Customer> getCustomers() {
		return customers;
	}
	public void setCustomers(List<Customer> customers) {
		this.customers = customers;
	}
}

五、项目整体预览图


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值