告别繁琐的配置文件 ---- 全注解Spring,Hibernate开发 不完全指南

告别繁琐!Spring的配置革命:一键部署你的Java帝国 告别手动配置的繁琐,拥抱Spring带来的配置革命!这篇文章将为你揭示如何使用Spring框架一键部署你的Java帝国。我们将深入探讨Spring的自动装配技术,展示如何通过属性文件轻松管理不同环境的配置,以及如何利用Profile功能在不同星际环境(开发、测试、生产)间无缝切换。这是一篇让你的Java应用部署变得前所未有的简单和震撼的文章! 阅读详情

当我最开始接触Spring和hibernate开发的时候,也是从别人(学长)那里拷贝过来一个项目,自己学习研究,在当时,像applicationContext.xml这种配置文件也是他写成什么样,我就跟着照猫画虎的改,甚是觉得别扭,程序是万能的,为何我们不能突破常规,选择一种提高我们开发效率的方式?

说时迟,那时快,我决定全部采用注解来配置我的web应用,当时也不知道是否可行,不过,经过我的实践,最后成功了,在这里与大家分享。

首先看一下我的Spring 配置文件 applicationContext.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:mvc="http://www.springframework.org/schema/context/mvc" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
	http://www.springframework.org/schema/context/mvc http://www.springframework.org/schema/context/mvc/spring-mvc-3.0.xsd">
    <aop:aspectj-autoproxy/>
	<!-- 配置数据源 -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="/WEB-INF/datasource-conf.properties"></property>
	</bean>

	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<property name="driverClass" value="${driverClass}" />
		<property name="jdbcUrl" value="${jdbcUrl}" />
		<property name="user" value="${user}" />
		<property name="password" value="${password}" />
		<property name="initialPoolSize" value="${initialPoolSize}"></property>
		<property name="minPoolSize" value="${minPoolSize}"></property>
		<property name="maxPoolSize" value="${maxPoolSize}"></property>
		<property name="maxIdleTime" value="${maxIdleTime}"></property>
		<property name="acquireIncrement" value="${acquireIncrement}"></property>
		<property name="idleConnectionTestPeriod" value="${idleConnectionTestPeriod}"></property>
		<property name="acquireRetryAttempts" value="${acquireRetryAttempts}"></property>
		<property name="breakAfterAcquireFailure" value="${breakAfterAcquireFailure}"></property>
		<property name="maxStatements" value="${maxStatements}"></property>
		<property name="testConnectionOnCheckout" value="${testConnectionOnCheckout}"></property>
	</bean>
    
	<!-- 启动注解自动装配 -->
	<bean
		class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

	<!-- 启动基于注解(annotation)驱动 MVC-->
	<context:component-scan base-package="net.woaoo">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	
	<!--基于注解映射的hibernateTemplate -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="annotatedClasses">
			<bean class="net.woaoo.common.config.EntityBeanFinderFactoryBean">
		        <property name="classNamePattern" value="net.woaoo.**.model.**"/>
      		</bean>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
			</props>
		</property>
	</bean>
	
	<!-- HibernateTemplate -->
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<!-- JDBCTemplate -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource" />
	</bean>
</beans>
我的修改主要有两点:

1.首先,bean不需要再配置文件中配置,在类中使用 @Repository  @Service 注解,spring会基于你的类名生成 首字母小写与之对应的对象,例如

@Service

public class ExampleService implements IExample{

} 
你可以这样调用:

@Autowired

IExample exampleService;

........

2.hibernate与数据库的映射类不通过手动配置,而是通过扫描的方式,这在一个新的项目的开发阶段很有帮助,能大大提高效率,数据库即便改来改去也不用修改配置文件,

传统的数据源dataSource 配置方式:

<property name="dataSource" ref="dataSource" />
		<property name="annotatedClasses">
			<list>
				<value>xxx.xxx.xxxModel</value>
				<value>.........</value>
			</list>			
		</property>
....
我的配置方式

<property name="dataSource" ref="dataSource" />
		<property name="annotatedClasses">
			<bean class="net.woaoo.common.config.EntityBeanFinderFactoryBean">
		        <property name="classNamePattern" value="net.woaoo.**.model.**"/>
      		</bean>
		</property>
........

这个方法是我在逛spring论坛上看到的, springsource.org

分享下这个类:

package net.woaoo.common.config;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;

/**
 * This class finds all @Entity annotated classes defined by an ANT style class name pattern. Default
 * pattern is **.domain.**
 * 
 * @author marcus.bristav@dreampark.com
 */
public class EntityBeanFinderFactoryBean implements ResourceLoaderAware,
        FactoryBean {
    private ResourcePatternResolver resolver;

    private List<Class> managedClasses = null;

    private String classPattern = "classpath*:**/domain/**/*.class";

    static final int UTF = 1, INTEGER = 3, FLOAT = 4, LONG = 5, DOUBLE = 6,
            CLASS = 7, STRING = 8, FIELD_REF = 9, METHOD_REF = 10,
            INTERFACE_METHOD_REF = 11, NAME_AND_TYPE = 12;

    public void setResourceLoader(ResourceLoader resourceLoader) {
        resolver = ResourcePatternUtils
                .getResourcePatternResolver(resourceLoader);
    }

    /**
     * Determines what class files to scan for @Entity annotations. The string 
     * behaves like ANT paths. Default value is "**.domain.**"
     * @param packagePattern
     */
    public void setClassNamePattern(String packagePattern) {
        classPattern = "classpath*:" + packagePattern.replace(".", "/")
                + "/*.class";
    }

    public Object getObject() throws Exception {
        if (managedClasses == null) {
            loadManagedClasses();
        }
        return managedClasses;
    }

    public Class getObjectType() {
        return List.class;
    }

    public boolean isSingleton() {
        return true;
    }

    private void loadManagedClasses() throws Exception {
        managedClasses = new ArrayList<Class>();
        Resource[] resources = resolver.getResources(classPattern);
        if (resources != null) {
            for (Resource res : resources) {
                Class klass = getClass(res);
                if (hasEntityAnnotation(klass)) {
                    managedClasses.add(klass);
                }
            }
        }
    }
    
    private Class getClass(Resource res) throws Exception{
        String className = className(res);
        System.out.println(className);
        return Class.forName(className);        
    }

    private boolean hasEntityAnnotation(Class klass) {
        return (klass.getAnnotation(javax.persistence.Entity.class) != null);
    }

    // Parses java class files (byte code) to find class name
    // Must be a better way to do this...
    private String className(Resource res) throws Exception {
        InputStream is = res.getInputStream();
        Map<Integer, Integer> offsetTable = new HashMap<Integer, Integer>();
        Map<Integer, String> classNameTable = new HashMap<Integer, String>();
        DataInputStream data = new DataInputStream(new BufferedInputStream(is));
        int magic = data.readInt();
        int minorVersion = data.readShort();
        int majorVersion = data.readShort();
        int constant_pool_count = data.readShort();
        int[] constant_pool = new int[constant_pool_count];
        for (int i = 1; i < constant_pool_count; i++) {
            int tag = data.read();
            int tableSize;
            switch (tag) {
            case CLASS:
                int offset = data.readShort();
                offsetTable.put(i, offset);
                break;
            case UTF:
                int length = data.readShort();
                char[] bytes = new char[length];
                for (int k = 0; k < bytes.length; k++)
                    bytes[k] = (char) data.read();
                String className = new String(bytes);
                classNameTable.put(i, className);
                break;
            case LONG:
            case DOUBLE:
                data.readLong();
                i++;
                break;
            case STRING:
                data.readShort();
                break;
            default:
                data.readInt();
            }
        }
        short access_flags = data.readShort();
        int this_class = data.readShort();
        int super_class = data.readShort();
        String thisClassName = classNameTable.get(offsetTable.get(this_class));
        is.close();
        return thisClassName.replace("/", ".");
    }
}


spring mvc spring4.x hibernate4.注解方式注入 spring mvc spring4.x hibernate4.注解方式注入 简单的例子.spring mvc spring4.x hibernate4.注解方式注入 简单的例子. 立即下载

相关推荐

如何处理MIGO取消物料凭证报错:“只是可能对有相同的价格控制进行倒记账(本月S,前月V)” & “仅在 QM 中修改物料质量检验库存”

记录一次处理MM模块的报错。这次连续处理了两个错误,“只是可能对有相同的价格控制进行倒记账(本月S,前月V)” & “仅在 QM 中修改物料质量检验库存”。把过程和操作步骤记录下一。方便日后回头查找。

IT小职员 6243

Spring注解大全(史上最全,字母编号,有实例)

目录 A @Accessors 链式编程使用。需要搭配@Getter和@Setter使用。主要有三个参数: 序号 参数名 介绍 1 chain 链式 2 fluent 流式(若无显示指定chain的值,也会把chain设置为true) 3 prefix 生成指定前缀的属性的getter与setter方法,并且生成的getter与setter方法时会去除前缀 我们发现prefix可以在生成get/set的时候,去掉xxx等prefix前缀,达到很好的一致性。但是,

qq_46138160的博客 9932

ArcMap 10.7/10.8启动加载界面后闪退?可能是这个隐藏的Normal.mxt模板文件在搞鬼

本文深入分析了ArcMap 10.7/10.8启动加载界面后闪退的问题,指出Normal.mxt模板文件损坏是常见原因。提供了从定位、删除模板文件到系统级修复的完整解决方案,帮助GIS工程师快速恢复工作流程。

weixin_28523493的博客 348

spring常用注解(全)

spring常用注解(全)

zhaoshuangjian 3857

在x86机器上运行jailhouse

jailhouse jaihouse提供了一个demo ,https://github.com/siemens/jailhouse-images可以用于编译一整套可用的demo。 适用于多个平台。编译过程主要参考https://blog.csdn.net/weixin_39541632/article/details/110422345 此demo可以生成多个平台所用的操作系统image。 ...

闲人的专栏 3016

IgH EtherCAT 从入门到精通:第 5 章 多主站与系统集成配置

本文介绍了 EtherCAT 多主站配置与系统集成方法。主要内容包括: 多主站实例配置原理:通过内核模块参数指定多个主站设备,每个主站独立管理一条 EtherCAT 总线,最多支持32个主站实例。 配置文件详解:在/etc/ethercat.conf中通过MASTER<X>_DEVICE变量定义各主站绑定的网卡或MAC地址,支持冗余备份配置。 系统服务集成:提供了systemd服务单元文件和传统init.d脚本两种方式实现开机自启动和管理,并建议通过override文件定制服务依赖关系。 架构示

从事嵌入式linux android驱动开发,拥有全栈能力 374

Spring-全注解开发

Junit 是单元测试工具,在开发过程中,使用Junit进行单元测试,可以免去很多不必要的麻烦以及重启项目的操作。注解开发优点: 全注解开发可以省去配置文件,直接在代码添加@注解即可达到相同效果,开发效率以及代码阅读等都大大提高。注:文末有所有Maven引用依赖坐标,本地编写代码先引入所有依赖,否则会报错。4、更新安装环境,安装mysql,设置mysql的root密码。后面我会写一个完整的搭建方式,以及标准安全的正常配置。2、创建虚拟机, 下载Ubuntu的镜像文件。​ (2)定义Mybatis配置类。

菜鸟 1271

Fiori Elements 从入门到精通开发教程的文章目录

Fiori Elements 开发技术相对 SAP 其他历史悠久,发展成熟的开发技术来说,是一个新事物。正因如此,迄今为止国内深入讲解 Fiori Elements 应用的中文材料几乎没有。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 5427

Spring全注解开发---常用注解笔记整理,【工作感悟】

{ } peo没被扫描进来,完美 []( )@Scope ===================================================================== @Configuration //标注当前是一个配置类 @ComponentScan(value = “com.controller”) public class MyConfig { @Scope(“prototype”) @Bean(value = “dhy”)//指定id public people g

m0_63174420的博客 287

零基础入门simulink建模仿真--基于Simulink的QPSK调制与解调仿真建模示例

QPSK是一种相位调制技术,将两个比特映射到一个符号上,每个符号对应四个可能的相位之一(0°、90°、180°、270°)。通过Simulink,我们可以通过模块化的建模方式实现QPSK的调制和解调过程,并观察信号在信道中的传输效果。通过本指南,我们介绍了如何基于Simulink搭建一个完整的QPSK调制与解调仿真模型,并进行仿真和性能评估。背景介绍:理解QPSK调制与解调的基本原理及其应用。所需工具和环境:列出进行QPSK仿真所需的工具和环境。步骤详解。

amy_mhd的博客 1320

【人工智能】Claude服务访问受限报错的技术分析与解决方案

在使用Claude系列大模型服务的过程中,部分用户会遇到服务不可用的标准化拦截提示,导致无法正常访问模型核心能力。本文针对该类报错进行完整技术拆解,明确报错根因与底层校验逻辑,并分场景提供合规、可落地的排查与解决方案,同时规避相关使用风险。

奶爸的编程之路,也就一周冷个三天 2732

Struts2.1.6+Spring2.5.6+Hibernate3.3.1全注解实例详解(三)

转自:Struts2.1.6+Spring2.5.6+Hibernate3.3.1全注解实例详解(三)   在前两章我为大家详细分析了JAR包的选择和必须的配置文件,那么这一章,我就对例子的层次结构进行说明,并实现除WEB层的功能代码。    第三部分:建立框架代码    工程结构        大家可以看到,本例一共分为:dao、entity、service、web四层。另外在这些层次下,...

阿O、不拽 140

【花雕动手做】行空板K10系列实验之通过Wi-Fi和MQTT协议搭建Siot物联网服务平台

SIoT为一个为中小学STEM教育定制的跨平台的开源MQTT服务器程序,S指科学(Science)、简单(Simple)的意思。MQTT(Message Queuing Telemetry Transport)是一种轻量级的、基于发布/订阅模式的消息传输协议,广泛应用于物联网(IoT)设备之间的数据通信。主题(Topic):主题是消息的分类标签,发布者和订阅者通过主题进行消息的传递和接收。发布/订阅模式:设备通过主题(Topic)进行消息的发布和订阅,消息代理(Broker)负责接收和转发消息。

雕爷学编程 1432

Struts2.1.6+Spring2.5.6+Hibernate3.3.1全注解实例详解(三)(转载大象)

在前两章我为大家详细分析了JAR包的选择和必须的配置文件,那么这一章,我就对例子的层次结构进行说明,并实现除WEB层的功能代码。    第三部分:建立框架代码    工程结构        大家可以看到,本例一共分为:dao、entity、service、web四层。另外在这些层次下,还以业务功能再进行分包,这样做是为了方便在以后的功能扩展中,能更好的管理和维护代码。如果将所有类都直接集中在这4个...

skyqqzhou的专栏 165

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

SSH全注解实例详解(3)(转)

转载地址:http://www.java3z.com/cwbwebhome/article/article8/81137.html?id=2584 在前两章我为大家详细分析了JAR包的选择和必须的配置文件,那么这一章,我就对例子的 层次结构进行说明,并实现除WEB层的功能代码。     第三部分:建立框架代码     工程结构          大家可以看到,本例一共分为:dao、...

iteye_13151的博客 149

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

学习SSH全注解实例过程(三)

原文链接: http://www.java3z.com/cwbwebhome/article/article8/81137.html 在前两章我为大家详细分析了 JAR 包的选择和必须的配置文件,那么这一章,我就对例子的层次结构进行说明,并实现除 WEB 层的功能代码。      第三部分:建立框架代码      工程结构     ...

永不止步 113

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

上一篇: 2011蓝桥杯Java决赛 连通问题
下一篇: gson转换Timestamp类型 "2012-11-3 10:49:15" --> "2012-11-03 10:49:15"
逆乾坤
博客等级 码龄16年 30粉丝 18原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址