spring能使用注解给非get set的普通方法 参数注入不?

例如createJdbcTemplate(DataSource dataSource)
我想使用注解 给ds注入

3个回答

可以,spring不仅支持getter、setter等方法级别的注入,也支持其他costomer method的注入。

lingshao0426
lingshao0426 擦 就是加了 不成功 才问的.... 那估计不是这个问题
6 年多之前 回复
iteye_14005
iteye_14005 方法上或者参数前jia@Autowired都可以
6 年多之前 回复
lingshao0426
lingshao0426 擦 给个 例子呗? 直接在方法上面@autowired?
6 年多之前 回复

支持 如使用

@Autowired
public void createJdbcTemplate(Ds)

huo

public void createJdbcTemplate(@Autowired Ds)

jinnianshilongnian
jinnianshilongnian 建议你贴下配置
6 年多之前 回复
lingshao0426
lingshao0426 额 我就是这样写的 我继承jdbctemplate 然后 给这个类添加了 component注解 也扫描进去了 就是注入不成功 不知道什么原因
6 年多之前 回复

<bean
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" ref="test"></property>
    <property name="targetMethod" value="app"></property>
    <property name="arguments">
       <list>
          <value>a</value>
          <value>b</value>
       </list>

    </property>
</bean>

参考一下这个,然后 Test 这个 class 里面有个 app 方法,里面有两个参数

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
spring data jpa 使用注解(AbstractRoutingDataSource)实现多数据源,定时任务和新建线程的方法,却无法进行数据库操作?
Spring boot2.X项目,使用data jpa 框架,普通方法可以实现数据源的切换,但是新建线程和定时任务里面执行方法,却不能插入和修改数据库,并且控制端无日志输出。可以查询数据。 相同的多数据源配置,使用mybatis框架不存在这样的情况。 ``` /** * 数据源配置 */ @Configuration public class DataSourceConfig { @Autowired private DBProperties properties; @Bean(name = "dataSource") public DataSource dataSource() { //按照目标数据源名称和目标数据源对象的映射存放在Map中 Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put("first", properties.getFirst()); targetDataSources.put("second", properties.getSecond()); targetDataSources.put("third", properties.getThird()); //采用是想AbstractRoutingDataSource的对象包装多数据源 DynamicDataSource dataSource = new DynamicDataSource(); dataSource.setTargetDataSources(targetDataSources); //设置默认的数据源,当拿不到数据源时,使用此配置 dataSource.setDefaultTargetDataSource(properties.getFirst()); return dataSource; } @Bean public PlatformTransactionManager transactionManager() { return new DataSourceTransactionManager(dataSource()); } } ``` 补充: ``` @Scheduled(cron = "0 0/1 * * * ?") public void aioCallMethod() { System.out.println("timer start"); Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); if (hour == 21) { calendar.set(Calendar.HOUR_OF_DAY, 9); } else { calendar.set(Calendar.HOUR_OF_DAY, 21); calendar.add(Calendar.DATE, -1); } calendar.set(Calendar.MINUTE, 30); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); Date date1 = calendar.getTime(); calendar.add(Calendar.HOUR_OF_DAY, 12); Date date2 = calendar.getTime(); Date date = DateUtil.toDate(new Date(), "yyyy-MM-dd"); List<DiamondWireRecord> diamondWireRecords = new ArrayList<>(); DiamondWireRecord diamondWireRecord; String deviceNo; List<EquipmentAccessory> equipmentAccessories = equipmentAccessoryService.findAll(); for (EquipmentAccessory equipmentAccessory : equipmentAccessories) { //设备编号 deviceNo = equipmentAccessory.getDeviceNo(); diamondWireRecord = new DiamondWireRecord(); //记录时间 diamondWireRecord.setCreateDate(date); diamondWireRecord.setDeviceNo(deviceNo); diamondWireRecords.add(diamondWireRecord); } System.out.println("update start"); if (diamondWireRecords.size() > 0) { diamondWireRecordService.saveAll(diamondWireRecords); } System.out.println("update end"); } ```
spring如何在Aspect中获取切点注解方法的泛型参数类型
业务场景是这样:想要做一个自定义注解@MethodCache,注解方法,功能是通过Aspect切片来自动缓存方法结果 ``` @Target({ METHOD }) @Retention(RUNTIME) public @interface MethodCache { /** * 过期时间 单位秒 默认60秒 */ int expire() default 60; } ``` Aspect类 ``` @Aspect @Configuration public class MethodCacheAnnotationAspect { // 日志 private Logger logger = LoggerFactory.getLogger(MethodCacheAnnotationAspect.class); //redis @Autowired private RedisTemplate bbscache; // around 建言 切入点为匹配注解了@MethodCache @Around("@annotation(com.ewt360.bbsapi.service.component.MethodCache)") public Object cacheProcess(ProceedingJoinPoint jp) throws Throwable { Class<?> targetClz = jp.getTarget().getClass(); String methodName = jp.getSignature().getName(); if(!(jp.getSignature() instanceof MethodSignature)){ logger.warn("该方法接口无法启用缓存功能: {}", jp.getSignature().toLongString()); return jp.proceed(); } MethodSignature methodSign = (MethodSignature)jp.getSignature(); MethodCache sc = methodSign.getMethod().getAnnotation(MethodCache.class); if (sc == null) return jp.proceed(); int expire = sc.expire() > 0 ? sc.expire() : 200; // 组装缓存key String cacheKey = buildCacheKey(targetClz, methodName, jp.getArgs()); logger.info("cacheInvoke =>{}",cacheKey); Object rval = cacheInvoke(sc, methodSign, jp, cacheKey, expire); return rval; } private String buildCacheKey(Class targetClz, String methodName, Object[] args){ return targetClz.getPackage()+methodName+ StringUtils.arrayToDelimitedString(args, "."); } private Object cacheInvoke(MethodCache sc, MethodSignature methodSign, ProceedingJoinPoint jp, String cacheKey, int expire) throws Throwable { //得到方法的结果类型 Class returnClazz = methodSign.getReturnType(); Object result; Object rval = bbscache.opsForValue().get(cacheKey); if (rval == null) { logger.info("miss from cache, load backend for key : {}", cacheKey); result = jp.proceed(); if(result != null){ logger.info("cache to redis {},{}", cacheKey, JSON.toJSONString(result)); bbscache.opsForValue().set(cacheKey, result, expire, TimeUnit.SECONDS); } } else{ if(ObjectUtils.isBaseType(returnClazz)){ result = rval; } else { JSON.parseObject((String) rval, new TypeReference<List<Integer>>() {}); result = JSONObject.toJavaObject((JSON) rval, returnClazz); } logger.info("cache get object: {}", JSON.toJSONString(rval)); } return result; } } ``` 使用的时候只要在方法上加上注解就ok ``` @MethodCache() public List<Integer> testInt() { List<Integer> list = new ArrayList<>(); list.add(0); list.add(1); return list; } ``` 利用redis缓存方法执行结果,如果已缓存则将缓存转换为方法出参类型,正常的参数类型都OK的,可以得到方法的结果类型,但是如果是泛型类型的话,比如List和map, 却只能得到List,Map类型,并不能得到确切的泛型类型,比如 ``` List<Map<String,String>> List<User> Map<String, User> ``` 只能解出 ``` List<JSONObject> Map<Object, JSONObject> ``` 因为泛型的类型擦除,所以很难做到,也想过在注解里面传入具体类型,但是也没办法把泛型类型传进来,这个要怎么做,希望大家提供思路!!
springboot2.1.4 + jpa + hibernate 使用aop注解形式实现多数据源管理 可能懒加载出现问题求大神解答
最近项目中使用springboot2.1.4 + jpa + hibernate 使用aop注解形式实现多数据源管理,用的就是网上大多数人使用的一套代码,但是我在项目中使用后发现如果配置 spring配置文件 application.yml 中open-in-view: false 跨数据源查询正常,但是保存或者修改失败原因是事务没有提交,一旦把open-in-view改成true则不能跨数据源查询,修改保存正常事务正常提交求解,具体代码如下实现 1. application.yml ``` spring: ## 数据库配置 #datasource: #driver-class-name: com.mysql.jdbc.Driver #url: jdbc:mysql://192.168.101.125:3306/cdv?useSSL=false&characterEncoding=utf-8 #username: root #password: 123456 #url: jdbc:mysql://127.0.0.1:3306/boot-jpa-back-sys2?useSSL=false&characterEncoding=utf-8 #username: root #password: datasource: test1: driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://192.168.101.125:3306/cdv?useSSL=false&characterEncoding=utf-8 username: root password: 123456 type: com.alibaba.druid.pool.DruidDataSource test2: driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver jdbc-url: jdbc:sqlserver://192.168.101.125:1433;database=Test; username: sa password: Zqvideo123 type: com.alibaba.druid.pool.DruidDataSource ## jpa配置 jpa: show-sql: true hibernate: #ddl-auto: update properties: hibernate.dialect: com.common.mysql.MySQLDialectUTF8 hibernate.format_sql: false open-in-view: false ``` DataSourceAsepct ``` package com.common.db; import java.lang.reflect.Method; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Aspect @Component @Order(0) public class DataSourceAsepct { //加载数据源 @Pointcut("@annotation(com.common.db.DataSourceSet)") // @AfterThrowing(pointcut="@annotation(com.common.db.DataSource)", throwing= "error") public void pointCut(){ } @Before("pointCut()") public void before(JoinPoint joinPoint) { Object target = joinPoint.getTarget(); MethodSignature signature = (MethodSignature) joinPoint.getSignature(); DataSourceEnum dataSource = DataSourceEnum.DEFAULT; try { Method method = target.getClass().getMethod(signature.getName(), signature.getParameterTypes()); if (method.isAnnotationPresent(DataSourceSet.class)) { DataSourceSet annotation = method.getAnnotation(DataSourceSet.class); dataSource = annotation.value(); } } catch (NoSuchMethodException e) { e.printStackTrace(); } //实现aop切换数据源 System.out.println("aop切换数据源:" + dataSource.getName()); DataSourceHolder.setDataSource(dataSource); } // @After("pointCut()") @AfterThrowing(pointcut="@annotation(com.common.db.DataSourceSet)", throwing= "error") public void after() { DataSourceHolder.clearDataSource(); String v = DataSourceHolder.getDataSource(); System.out.println(v); } } ``` DataSourceConfig ``` package com.common.db; import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.jta.JtaTransactionManager; @Configuration public class DataSourceConfig { //连接数据库db1 @Bean("test1") @ConfigurationProperties("spring.datasource.test1") public DataSource test1() { return DataSourceBuilder.create().build(); } //连接数据库db2 @Bean("test2") @ConfigurationProperties("spring.datasource.test2") public DataSource test2() { return DataSourceBuilder.create().build(); } @Bean("dynamicDataSource") @Primary public DataSource dynamicDataSource() { DynamicDataSource dataSource = new DynamicDataSource(); dataSource.setDefaultTargetDataSource(test1()); Map<Object, Object> dataSourceMap = new HashMap<>(2); dataSourceMap.put(DataSourceEnum.TEST1.getName(), test1()); dataSourceMap.put(DataSourceEnum.TEST2.getName(), test2()); dataSource.setTargetDataSources(dataSourceMap); return dataSource ; } @Bean public PlatformTransactionManager transactionManager() { return new DataSourceTransactionManager(dynamicDataSource()); } } ``` DataSourceEnum ``` package com.common.db; import lombok.AllArgsConstructor; import lombok.Getter; @AllArgsConstructor @Getter public enum DataSourceEnum { DEFAULT("test1"), TEST1("test1"), TEST2("test2"); private String name; } ``` DataSourceHolder ``` package com.common.db; public class DataSourceHolder { private static final ThreadLocal<String> DS_HOLDER = new ThreadLocal<>(); public static void setDataSource(DataSourceEnum dataSource) { DS_HOLDER.set(dataSource.getName()); } public static String getDataSource() { return DS_HOLDER.get(); } public static void clearDataSource() { DS_HOLDER.remove(); } } ``` DataSourceSet ``` package com.common.db; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Documented public @interface DataSourceSet { //枚举 DataSourceEnum value(); } ``` DynamicDataSource ``` package com.common.db; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { //基于aop切换数据源 System.out.println("dynamic datasource 切换数据源" + DataSourceHolder.getDataSource()); return DataSourceHolder.getDataSource(); } } ``` 测试调用 ``` server层 @Override @DataSourceSet(DataSourceEnum.TEST1) public String test1(Long id) { String s = programRepository.findids(id); System.out.println(s); return s; } @Override @DataSourceSet(DataSourceEnum.TEST2) public String test2(Long id) { String s = testRepository.findids1(id); System.out.println(s); return s; } ``` ``` Controller层 @PostMapping("/test") @ResponseBody public ResultVo test(Long id) { id = 1l; String beProgram1 = programService.test1(id); System.out.println(222); id=2l; String beProgram = testService.test2(id); System.out.println(333); return ResultVoUtil.success(beProgram+beProgram1); } ```
dwr框架结合Spring框架不能调用DAO方法
想用dwr框架做一个不刷新页面,验证用户名存不存在的方法,但是页面始终无法实现方法,后台不报错,只是在JSP页面上弹出ERROR错误。 后台已经测试,可以正确进入对应方法CheckData,并且email也传入进去了,但就是不能调用userBiz方法。 怀疑跟Spring框架结合有错误,两次查询了Spring配置,都是正确的,请问何解? 下面贴jsp相关代码: [code="java"] /*邮箱名是否注册检查*/ function checkResult1(){ var result=null; var email = document.getElementById('email').value; if(email <= 5){ result='<span class="STYLE7">用户名必须大于5个字符</span>'; document.getElementById('result1').innerHTML=result; }else if(email > 50){ result='<span class="STYLE7">用户名必须小于50个字符</span>'; document.getElementById('result1').innerHTML=result; }else{ CheckOccupied.checkEmailOccupied(email,msg1); } } function msg1(data){ var result = null; if(data == "yes"){ result='<img src="../images/check_right.gif" alt="">'; }else if(data == "no"){ result='<span class="STYLE7">该用户名已注册,请更换用户名或<a href="#">登录</a></span>'; }else{ result='数据错误'; } document.getElementById('result1').innerHTML=result; } [/code] spring框架相关代码: [code="java"] <!-- 声明事务管理器 --> <bean id="myHibTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 基于@Transactional注解方式的事务管理 --> <tx:annotation-driven transaction-manager="myHibTransactionManager" /> <!-- 定义事务通知 --> <tx:advice id="txAdvice" transaction-manager="myHibTransactionManager"> <!-- 指定事务传播规则 --> <tx:attributes> <!-- 对get打头的方法应用SUPPORTS事务规则 --> <tx:method name="get*" propagation="SUPPORTS" /> <!-- 对其他方法应用REQUIRED事务规则 --> <tx:method name="*" propagation="REQUIRED"></tx:method> </tx:attributes> </tx:advice> <!-- 定义切面,并将事务通知和切面组合(定义哪些方法应用事务规则) --> <aop:config> <!-- 对com.tyyf.biz包下的所有类的所有方法都应用事务规则 --> <aop:pointcut id="bizMethods" expression="execution(* com.tyyf.biz.*.*(..))" /> <!-- 将事务通知和切面组合 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="bizMethods" /> </aop:config> <bean id="checkData" class="com.tyyf.dwr.CheckData" scope="prototype"> <property name="userBiz" ref="userBiz" /> </bean> [/code] java代码: [code="java"] User user = new User(); // 使用UserBiz接声明属性userBiz,并添加set方法,用于依赖注入 UserBiz userBiz; public void setUserBiz(UserBiz userBiz) { this.userBiz = userBiz; } public String checkEmailOccupied(String email) { user.setEmail(email); if (userBiz.getUser(user) != null) { return "no"; } else { return "yes"; } } [/code] dwr配置代码: [code="java"] <dwr> <allow> <create creator="new" javascript="CheckOccupied"> <param name="class" value="com.tyyf.dwr.CheckData" /> </create> </allow> </dwr> [/code]
Spring MVC UT中的NPE
代码很简单,是对Srping MVC工程controller的一个测试,用的Junit框架。测试代码如下 ``` import static org.junit.Assert.*; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextHierarchy({ @ContextConfiguration(name="parent",locations="classpath:spring-test.xml"), @ContextConfiguration(name="child", locations="classpath:spring-test-web.xml") }) public class MomUserInfoControllerTest { private MockMvc mockMvc; @Autowired private WebApplicationContext wac; @Before public void setUp() throws Exception { mockMvc=MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void testBriefUser() throws Exception { mockMvc.perform(get("/briefUser/3")).andDo(MockMvcResultHandlers.print()).andReturn(); } ``` 但是这个case抛出了NPE,原因是我有个spring的拦截器,从request中取得一些信息,代码如下: ``` @Component public class I18nInterceptor extends AbstractInterceptor { private static final Logger logger = LoggerFactory.getLogger(I18nInterceptor.class); @Autowired private HttpServletRequest request; @Override public void preInvoke(MethodInvocation invocation) { WebApplicationContext wc =ContextLoader.getCurrentWebApplicationContext(); RequestInfo requestInfo = wc.getBean("requestInfo", RequestInfo.class); String locale = request.getParameter("locale"); logger.info("Set the locale to " + locale); ``` 问题来了..wc是空值,就是ContextLoader.getCurrentWebApplicationContext();娶不到值,因此该测试会有空指针,也无法进行下去。不知道大家有啥办法解决?我想应该是@RunWith(SpringJUnit4ClassRunner.class)这个注解导致了这个启动的webapplicationcontext的问题,不知道是不是
struts2注解url没跳转到action里的方法,没报错也没跳转
我补下图片: ![图片说明](https://img-ask.csdn.net/upload/201509/21/1442781387_310218.png) package com.AppServer.action; import javax.annotation.Resource; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.ExceptionMapping; import org.apache.struts2.convention.annotation.ExceptionMappings; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Service; import com.AppServer.bean.User; import com.AppServer.dao.UserDAO; import com.AppServer.service.UserService; import com.demo.interceptor.MethodCacheInterceptor; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; @Controller @ParentPackage("struts-default") @Namespace(value = "msgAction") @ExceptionMappings({ @ExceptionMapping(exception = "java.lange.RuntimeException", result = "error") }) public class MsgAction extends ActionSupport { private String username; private String password; @Resource private UserService userService; @Action(value = "msg" , results = { @Result(name = "success", location = "/success.jsp"), @Result(name = "failure", location = "/failure.jsp"), @Result(name = "error", location = "/login.jsp")}) //获取用户信息 public String getInfo() { System.out.println("进来玩"); return SUCCESS; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } url访问如下:http://127.0.0.1:8080/AppServer_1.1/msgAction/msg.do 访问之后没报错,没进去getInfo这个方法 struts2.xml: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- 指定Web应用的默认编码,相当于调用request的setCharacterEncoding方法 --> <constant name="struts.i18n.encoding" value="UTF-8" /> <!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 --> <constant name="struts.serve.static.browserCache" value="false" /> <!-- 当Struts2的配置文件修改后,系统是否自动重新加载配置文件,默认值为false(生产环境下使用),开发阶段最好打开 --> <constant name="struts.configuration.xml.reload" value="true" /> <!-- 开发模式下使用,这样可以打印出更详细的日志信息 --> <constant name="struts.devMode" value="true" /> <!-- 默认的视图主题 --> <constant name="struts.ui.theme" value="simple" /> <!-- 把Action对象交给Spring创建和管理 --> <constant name="struts.objectFactory" value="spring" /> <!-- Struts2处理的请求后缀,默认值是action --> <constant name="struts.action.extension" value="do" /> <!-- 国际化资源文件 <constant name="struts.custom.i18n.resources" value="globalMessages" /> --> <package name="msg" extends="struts-default"> <default-action-ref name="indexPage" /> <global-results> <result name="exceptionPage">/error/exceptionPage.jsp</result> </global-results> <global-exception-mappings> <exception-mapping result="exceptionPage" exception="java.lang.Exception" /> </global-exception-mappings> <action name="indexPage"> <result>/login.jsp</result> </action> <!-- <action name="msg" method="getInfo" class="com.AppServer.action.MsgAction"> <result name="success">/success.jsp</result> <result name="failure">/failure.jsp</result> <result name="error">/login.jsp</result> </action> --> </package> </struts> application.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:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd" default-autowire="byName" default-lazy-init="true"> <!-- 说明:下面有的Bean配置提供了多种方案,请根据需要采用某一种(别忘了注释掉其他同类方案) --> <!-- 自动扫描Spring注解配置 并保证@Required,@Autowired的属性被注入--> <context:component-scan base-package="com" /> <!-- 自动加载属性配置文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 配置数据源:方法一,使用C3P0方式(推荐) --> <!-- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" --> <!-- destroy-method="close" --> <!-- p:driverClass="${jdbc.driverClassName}" --> <!-- p:jdbcUrl="${jdbc.url}" --> <!-- p:user="${jdbc.username}" --> <!-- p:password="${jdbc.password}" /> --> <!-- <context:property-placeholder location="classpath:jdbc.properties"/> --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <!-- property池启动时的初始值 --> <property name="password" value="${jdbc.password}"/> <!-- 连接name="initialSize" value="${initialSize}"/>--> <property name="initialSize" value="1"/> <!-- 连接池的最大值 --> <property name="maxActive" value="500"/> <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --> <property name="maxIdle" value="2"/> <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 --> <property name="minIdle" value="1"/> </bean> <!-- 配置数据源:方法二,使用DBCP方式(不推荐) --> <!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> --> <!-- 配置数据源:方法三,使用JNDI方式 --> <!-- <jee:jndi-lookup id="dataSource" jndi-name="${jndi.name}" /> --> <!-- 配置Hibernate的数据源代理工厂:方法一,使用p属性通配符,按文件名搜索匹配的映射文件 --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" > <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> </props> </property> 加载hibernate的jpa注解形式实体 <property name="packagesToScan"> <list> <value>com.xmm.demo.domain*</value> </list> </property> </bean> --> <!-- 配置Hibernate的数据源代理工厂:方法二,使用list集合,按文件名搜索匹配的映射文件 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource"> <property name="mappingLocations"> <list> <value>classpath*:/com/**/*.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> </props> </property> </bean> <!-- 配置Hibernate的数据源代理工厂:方法三,使用p属性通配符,按目录搜索映射文件 --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:mappingDirectoryLocations="classpath*:/com/**/domain"> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> </props> </property> </bean> --> <!-- 配置Hibernate的数据源代理工厂:方法四,使用hibernate.cfg.xml --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:hibernate.cfg.xml"> </bean> --> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" /> <!-- 配置声明式事务:方法一,在Service实现类或者public实现方法上使用注解@Transactional,则此类或方法就会启用事务机制 --> <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <!-- 配置声明式事务:方法二,使用tx/aop命名空间的配置(其实还有方法三,由于快要过时不推荐使用了,这里就不给出方法三的配置了) --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="new*" propagation="REQUIRED" /> <tx:method name="set*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="change*" propagation="REQUIRED" /> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="load*" propagation="REQUIRED" read-only="true" /> <tx:method name="search*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" read-only="true" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="mypointcut" expression="execution(* com.**.service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="mypointcut" /> </aop:config> <!-- 下面三个Bean的配置可有可无,但配置后用处更大,通常用于BaseDao类、其他Dao类或特殊工具类中 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate" p:sessionFactory-ref="sessionFactory" /> <bean id="hibernateDaoSupport" class="org.springframework.orm.hibernate4.support.HibernateDaoSupport" p:hibernateTemplate-ref="hibernateTemplate" abstract="true"/> <bean id="sessionFactoryUtils" class="org.springframework.orm.hibernate4.SessionFactoryUtils" abstract="true"/> </beans> tomcat6.0:服务器运行正常: 九月 21, 2015 4:22:24 上午 org.apache.catalina.core.AprLifecycleListener init 信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: D:\Java\jdk1.7.0\bin;E:\tomcat6\bin 九月 21, 2015 4:22:25 上午 org.apache.coyote.http11.Http11Protocol init 信息: Initializing Coyote HTTP/1.1 on http-8080 九月 21, 2015 4:22:25 上午 org.apache.catalina.startup.Catalina load 信息: Initialization processed in 516 ms 九月 21, 2015 4:22:25 上午 org.apache.catalina.core.StandardService start 信息: Starting service Catalina 九月 21, 2015 4:22:25 上午 org.apache.catalina.core.StandardEngine start 信息: Starting Servlet Engine: Apache Tomcat/6.0.41 九月 21, 2015 4:22:25 上午 org.apache.catalina.startup.HostConfig deployDirectory 信息: Deploying web application directory AppServer_1.1 九月 21, 2015 4:22:25 上午 org.apache.catalina.loader.WebappClassLoader validateJarFile 信息: validateJarFile(E:\tomcat6\webapps\AppServer_1.1\WEB-INF\lib\servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class 九月 21, 2015 4:22:26 上午 org.apache.catalina.core.ApplicationContext log 信息: Set web app root system property: 'webapp.root' = [E:\tomcat6\webapps\AppServer_1.1\] 九月 21, 2015 4:22:26 上午 org.apache.catalina.core.ApplicationContext log 信息: Initializing log4j from [classpath:log4j.properties] 九月 21, 2015 4:22:26 上午 org.apache.catalina.core.ApplicationContext log 信息: Initializing Spring root WebApplicationContext 九月 21, 2015 4:22:34 上午 org.apache.coyote.http11.Http11Protocol start 信息: Starting Coyote HTTP/1.1 on http-8080 九月 21, 2015 4:22:34 上午 org.apache.jk.common.ChannelSocket init 信息: JK: ajp13 listening on /0.0.0.0:8009 九月 21, 2015 4:22:34 上午 org.apache.jk.server.JkMain start 信息: Jk running ID=0 time=0/23 config=null 九月 21, 2015 4:22:34 上午 org.apache.catalina.startup.Catalina start 信息: Server startup in 9364 ms 测试定时任务:2015-09-21 04:30:00:074 测试定时任务:2015-09-21 04:40:00:004 url访问地址:http://127.0.0.1:8080/AppServer_1.1/msgAction/msg.do 没有进去action的getinfo方法,这是为什么?而且也没有任何的报错!!!!!!!!!!!
spring mvc+hibernate4事务控制
``` web.xml <?xml version="1.0" encoding="UTF-8"?> <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"> <display-name>spring-mvc</display-name> <!--配置欢迎界面 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <error-page> <error-code>404</error-code> <location>/error/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/error/exception.jsp</location> </error-page> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- Log4j配置 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>WEB-INF/log4j.properties</param-value> </context-param> <!-- 开一条watchdog线程每60秒扫描一下配置文件的变化 --> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!--配置log4j包 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!--配置listener --> <!--在这里可以配置spring的监听器,启动的时候需要把spring中的bean都注册到spring容器中 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置filter对编码进行转换 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value><!-- 强制转码 --> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--配置servlet --> <!--我们希望spring的控制器比其他servlet优先启动,所以你需要设置load-on-startup 这个东西:值越小越先启动(0-5),没有或者为负数的时候,servlet被选用的时候才加载--> <servlet> <servlet-name>controller</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:controll-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>controller</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>sessionFactory</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> 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:dwr="http://www.directwebremoting.org/schema/spring-dwr" 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-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:hibernate.properties</value> </list> </property> </bean> <!-- DWR配置--> <dwr:annotation-config></dwr:annotation-config> <!-- 扫描需要转换的java对象 --> <dwr:annotation-scan scanRemoteProxy="true" base-package="com.tb.service" /> <!-- 部署项目时, 请把debug设为false <dwr:controller id="dwrController" debug="true" /> --> <!--DWR初始化配置 --> <dwr:configuration></dwr:configuration> <!-- 配置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>${db.driver}</value> </property> <property name="jdbcUrl"> <value>${db.url}</value> </property> <property name="user"> <value>${db.user}</value> </property> <property name="password"> <value>${db.password}</value> </property> <property name="maxPoolSize"> <value>300</value> </property> <property name="minPoolSize"> <value>1</value> </property> <property name="initialPoolSize"> <value>1</value> </property> <property name="maxIdleTime"> <value>60</value> </property> <property name="acquireIncrement"> <value>5</value> </property> <property name="acquireRetryAttempts"> <value>10</value> </property> <property name="acquireRetryDelay"> <value>1000</value> </property> <property name="autoCommitOnClose"> <value>true</value> </property> <property name="breakAfterAcquireFailure"> <value>false</value> </property> <property name="checkoutTimeout"> <value>100</value> </property> <property name="idleConnectionTestPeriod"> <value>60</value> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 让spring帮你扫描这个包底下的所有类,主要作用扫描跟数据库对应的实体类 --> <!-- 设置hibernate的属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.OracleDialect </prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.use_outer_join">true </prop> <prop key="hibernate.cglib.use_reflection_optimizer">true </prop> <prop key="hibernate.connection.useUnicode">true</prop> <prop key="hibernate.cache.use_query_cache">false</prop> <prop key="hibernate.default_batch_fetch_size">16</prop> <prop key="hibernate.c3p0.max_size">300</prop> <prop key="hibernate.c3p0.min_size">1</prop> <prop key="hibernate.c3p0.timeout">60</prop> <prop key="hibernate.c3p0.max_statements">100</prop> <prop key="hibernate.c3p0.idle_test_period">60</prop> <prop key="hibernate.c3p0.acquire_increment">5</prop> <prop key="hibernate.c3p0.validate">true</prop> <prop key="hibernate.current_session_context_class">thread</prop> </props> </property> <property name="packagesToScan" value="com.tb.model"/> </bean> <!--事务配置 --> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 开启AOP监听 只对当前配置文件有效 --> <aop:aspectj-autoproxy expose-proxy="true" /> <!-- 开启注解事务 只对当前配置文件有效 --> <tx:annotation-driven transaction-manager="txManager"/> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="merge*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="put*" propagation="REQUIRED" /> <tx:method name="execute*" propagation="REQUIRED" rollback-for ="Exception.class" /> <tx:method name="tes*" propagation="REQUIRED" /> <tx:method name="use*" propagation="REQUIRED" /> <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 --> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="count*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="list*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" rollback-for ="Exception.class"/> </tx:attributes> </tx:advice> <bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true" lazy-init="true"> <property name="transactionManager" ref="txManager"></property> <property name="transactionAttributes"> <props> <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="save*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="tes*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="execute*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="remove*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="query*">PROPAGATION_REQUIRED, readOnly,-Exception</prop> <prop key="load*">PROPAGATION_REQUIRED, -Exception</prop> </props> </property> </bean> <!-- 只对业务逻辑层实施事务 --> <aop:config expose-proxy="true"> <aop:pointcut id="txPointcut" expression="execution(* com.tb.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config> <!-- --> <!--配置拦截器 在springmvc的控制器配置文件中,你就可以这么配置拦截器,具体你在拦截器里面做什么,自己去做 <mvc:interceptors> 多个拦截器,顺序执行 <mvc:interceptor> 这里的path符号有/*, /**, *, ? 等,对于student.do?param=1从?开始不作为path 如果不配置或/*,将拦截所有的Controller <mvc:mapping path="/student/save*" /> <bean class="spring.common.interceptor.FromDupInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> --> </beans> controll-servlet.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: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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.tb"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <context:component-scan base-package="com.tb"/> <!-- json --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jsonHttpMessageConverter"/> </list> </property> </bean> <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- ③:对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" valu-e=".jsp"/> </bean> </beans> 以上为配置文件:包路径分别为com.tb.action;com.tb.service;com.tb.model;com.tb.dao; 其中com.tb.service下面又分com.tb.service.impl;com.tb.dao包下又分com.tb.dao.impl; 但是现在测试事物一直控制不了,请大神帮忙原因。测试方法: Controller.java @RequestMapping(params = "executeSearch") @Transactional public String executeSearch(HttpServletRequest request) { //测试事物控制。 infoService.test(); return "info/search"; } ServiceImpl.java public void test(){ try { infoDAO.test(); } catch (Exception e) { e.printStackTrace(); } } Service.java @Transactional public void test(); DaoImpl.java @Transactional public void test() { try { String sql = "update operation_log set username='1' where id='1'"; List<Object> condition = new ArrayList<Object>(); this.executeUpdateBySql(sql, condition); String sql1 = "update operation_log set username=33, where id='1'"; this.executeUpdateBySql(sql1, condition); } catch (RuntimeException e) { e.printStackTrace(); } } DaoImpl.java继承HibernateDao HibernateDao.java /***************注入***********/ @Resource private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession() { //事务配置后,可通过getCurrentSession方法获得session return sessionFactory.getCurrentSession(); } public int executeUpdateBySql(final String sql,final List<Object> conditions){ try { Query query = getSession().createSQLQuery(sql); if(conditions!=null && conditions.size()>0){ for(int i=0;i<conditions.size();i++){ if(conditions.get(i)!=null && !conditions.get(i).equals("")){ query.setParameter(i, conditions.get(i)); } } } return query.executeUpdate(); } catch (RuntimeException e) { throw e; }finally{ System.out.println(getSessionFactory().getCurrentSession().beginTransaction().isActive()); } } 整体代码是这样的,在运行daoImpl.java中test()方法的时候执行第一条SQL时会提交事物,直接修改数据库中的值,执行第二条SQL时会报错,理论上应该都不提交事物。但实际上第一条执行了之后就提交事物了,不知道是我框架问题还是我写的问题,求大神帮忙指出问题所在。万分感谢! ```
请教dwr
现在项目用的是dwr+struts2的方式,dwr可以进入struts2中的action方法,因为是分层 它无论如何都不能进入service层中的方法(注入的方式是注解注入),不知道是什么原因,请教! [b]问题补充:[/b] 在dwr中配置service层,我配了一个convert转换器, <convert match="com.joinintech.simfuni.service.OrderService" converter="bean"></convert> OrderService是服务的实现类,而在action中提供了service接口的get,set方法,其中service是以注解的方法进行注入的. [b]问题补充:[/b] 搞错了,配convert只是用来传数据用的,配一个create就可以了访问到action了,但是不能访问到service,原来用spring ioc方式,如果action能访问到,service也可以访问到,但是现在是注解注入,不知道是不是影响了. [b]问题补充:[/b] 那有什么解决办法吗?这个问题弄了很久了
请教spring 3+mybatis整合出错问题
spring 3+mybatis3+spring security整合,我的包和层次结构如下:采用的是按照模块分层, 每层有dao,sevrice,web三个目录,所有的实体类放在model文件夹中 security包中,有dao,service,web三个目录,其中 SecurityDao.java @MyBatisDao public interface SecurityDao extends BaseMapper<Security> { // 获得群组usergroups对应的权限 public List<Security> getGroupResources(); } SecurityService.java接口 ``` public interface SecurityService extends BaseService<Security> { public List<Security> getGroupResources(); } ``` SecurityServiceImpl .java @Service(value = "securityService") public class SecurityServiceImpl implements SecurityService { @Autowired private SecurityDao securityDao; // 获得群组usergroups对应的权限 public List<Security> getGroupResources() { return securityDao.getGroupResources(); } } MyBatisDao.java ``` /** * 标识MyBatis的DAO,方便{@link org.mybatis.spring.mapper.MapperScannerConfigurer}的扫描。 * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Component public @interface MyBatisDao { /** * The value may indicate a suggestion for a logical component name, * to be turned into a Spring bean in case of an autodetected component. * @return the suggested component name, if any */ String value() default ""; } ``` 然后系统有一个model的包,存放各模块的实体类这里有security.java,get/set就省略 了, 然后在maven的resource下建立文件src\resource\mappings\modules\security\SecurityDao.xml ``` <mapper namespace="com.liao.modules.core.security.dao.SecurityDao"> <resultMap id="getUserInfoMap" type="Security"> <result property="userid" column="userid"/> <result property="username" column="username"/> <result property="password" column="password"/> <result property="enabled" column="enabled"/> </resultMap> <select id="getGroupResources" resultType="Security"> select g.role_name roleName,a.url resourceValue from usergroups g join groupauthority_mapping ga on g.groupid=ga.groupid join authority a on ga.authorityid=a.authorityid </select> ``` spring-mvc.xml: ``` <!-- 自动扫描bean,把作了注解的类转换为bean --> <context:component-scan base-package="com.liao" > <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> ``` 其他mvc配置省略 spring-context-application.xml: ``` <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动匹配Mapper映射文件 --> <property name="mapperLocations" value="classpath:mappings/**/*.xml"/> <property name="typeAliasesPackage" value="com.liao.model"/> <property name="configLocation" value="classpath:/mybatis-config.xml"></property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.liao" /> <property name="annotationClass" value="com.itownet.isms.core.annotation.MyBatisDao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 事务配置 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> ``` mybatis-config.xml: ``` <configuration> <!-- 全局参数 --> <settings> <!-- 使全局的映射器启用或禁用缓存。 --> <setting name="cacheEnabled" value="true"/> <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载。 --> <setting name="aggressiveLazyLoading" value="true"/> <!-- 是否允许单条sql 返回多个数据集 (取决于驱动的兼容性) default:true --> <setting name="multipleResultSetsEnabled" value="true"/> <!-- 是否可以使用列的别名 (取决于驱动的兼容性) default:true --> <setting name="useColumnLabel" value="true"/> <!-- 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。 default:false --> <setting name="useGeneratedKeys" value="false"/> <!-- 指定 MyBatis 如何自动映射 数据基表的列 NONE:不隐射 PARTIAL:部分 FULL:全部 --> <setting name="autoMappingBehavior" value="PARTIAL"/> <!-- 这是默认的执行类型 (SIMPLE: 简单; REUSE: 执行器可能重复使用prepared statements语句;BATCH: 执行器可以重复执行语句和批量更新) --> <setting name="defaultExecutorType" value="SIMPLE"/> <!-- 使用驼峰命名法转换字段。 --> <setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 设置本地缓存范围 session:就会有数据的共享 statement:语句范围 (这样就不会有数据的共享 ) defalut:session --> <setting name="localCacheScope" value="SESSION"/> <!-- 设置但JDBC类型为空时,某些驱动程序 要指定值,default:OTHER,插入空值时不需要指定类型 --> <setting name="jdbcTypeForNull" value="NULL"/> </settings> ``` 在spring secrutiy中,调用 ``` public class DefinitionSourceFactoryBean implements FilterInvocationSecurityMetadataSource { @Autowired private SecurityService securityService; public void findResources() { List<Security> resourcesgroup = securityService.getGroupResources(); } } ``` 这个时候在运行securityService.getGroupResources();,说: mybatis,Invalid bound statement (not found): com.liao.core.security.dao.SecurityDao.getGroupResources 编译后,已经检查过,maoper.xml在web-inf\classes目录下了,为什么呢?
maven spring和ibatis的整合遇到的问题
下面两个是我的spring-ibatis的整合,另一个是sqlmapconfig.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <!-- 配置数据源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="2" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="1" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <property name="validationQuery" value="${validationQuery}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> <property name="filters" value="mergeStat" /> </bean> **strong text** **<!-- ibatis sqlMapClient 配置 让spring来管理SqlMapClient对象--> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="classpath:sqlmapconfig.xml"/> <property name="dataSource" ref="dataSource"/> </bean>** <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 注解方式配置事物 --> <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <!-- 拦截器方式配置事物 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="append*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="repair" propagation="REQUIRED" /> <tx:method name="delAndRepair" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" /> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="search*" propagation="SUPPORTS" /> <tx:method name="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* hyl.service..*Impl.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> <!-- 配置druid监控spring jdbc --> <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"> </bean> <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype"> <property name="patterns"> <list> <value>hyl.service.*</value> </list> </property> </bean> <aop:config> <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" /> </aop:config> </beans> 这是sqlmapconfig.xml的配置 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <sqlMap resource="classpath:hyl/sqlMap/TUSER_SqlMap.xml" /> </sqlMapConfig> 加粗的是后台提示的错误,嵌套错误:下面是错误的提示 [org.springframework.context.support.ClassPathXmlApplicationContext]Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@bfea1d: startup date [Thu Jan 16 17:17:54 CST 2014]; root of context hierarchy [org.springframework.beans.factory.xml.XmlBeanDefinitionReader]Loading XML bean definitions from class path resource [spring.xml] [org.springframework.beans.factory.xml.XmlBeanDefinitionReader]Loading XML bean definitions from class path resource [spring-ibatis.xml] [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer]Loading properties file from class path resource [config.properties] [org.springframework.beans.factory.support.DefaultListableBeanFactory]Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1bbd7b2: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,dataSource,sqlMapClient,transactionManager,transactionAdvice,org.springframework.aop.config.internalAutoProxyCreator,transactionPointcut,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0,druid-stat-interceptor,druid-stat-pointcut,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#1,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy [com.alibaba.druid.pool.DruidAbstractDataSource]maxIdle is deprecated [com.alibaba.druid.pool.DruidDataSource]{dataSource-1} inited [org.springframework.beans.factory.support.DefaultListableBeanFactory]Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1bbd7b2: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,dataSource,sqlMapClient,transactionManager,transactionAdvice,org.springframework.aop.config.internalAutoProxyCreator,transactionPointcut,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0,druid-stat-interceptor,druid-stat-pointcut,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#1,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy [com.alibaba.druid.pool.DruidDataSource]{dataSource-1} closed Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlMapClient' defined in class path resource [spring-ibatis.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse config resource: class path resource [sqlmapconfig.xml]; nested exception is com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: java.lang.RuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource classpath:hyl/sqlMap/TUSER_SqlMap.xml at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:591) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93) at hyl.test.Test.main(Test.java:13) Caused by: org.springframework.core.NestedIOException: Failed to parse config resource: class path resource [sqlmapconfig.xml]; nested exception is com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: java.lang.RuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource classpath:hyl/sqlMap/TUSER_SqlMap.xml at org.springframework.orm.ibatis.SqlMapClientFactoryBean.buildSqlMapClient(SqlMapClientFactoryBean.java:341) at org.springframework.orm.ibatis.SqlMapClientFactoryBean.afterPropertiesSet(SqlMapClientFactoryBean.java:291) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452) ... 12 more Caused by: com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: java.lang.RuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource classpath:hyl/sqlMap/TUSER_SqlMap.xml at com.ibatis.common.xml.NodeletParser.parse(NodeletParser.java:62) at com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser.parse(SqlMapConfigParser.java:62) at com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser.parse(SqlMapConfigParser.java:55) at org.springframework.orm.ibatis.SqlMapClientFactoryBean.buildSqlMapClient(SqlMapClientFactoryBean.java:338) ... 15 more Caused by: java.lang.RuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource classpath:hyl/sqlMap/TUSER_SqlMap.xml at com.ibatis.common.xml.NodeletParser.processNodelet(NodeletParser.java:123) at com.ibatis.common.xml.NodeletParser.process(NodeletParser.java:84) at com.ibatis.common.xml.NodeletParser.process(NodeletParser.java:102) at com.ibatis.common.xml.NodeletParser.parse(NodeletParser.java:72) at com.ibatis.common.xml.NodeletParser.parse(NodeletParser.java:60) ... 18 more Caused by: java.io.IOException: Could not find resource classpath:hyl/sqlMap/TUSER_SqlMap.xml at com.ibatis.common.resources.Resources.getResourceAsStream(Resources.java:110) at com.ibatis.common.resources.Resources.getResourceAsStream(Resources.java:95) at com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser$10.process(SqlMapConfigParser.java:249) at com.ibatis.common.xml.NodeletParser.processNodelet(NodeletParser.java:121) ... 22 more 下面的是我TUSER_SqlMap.xml文件 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd" > <sqlMap namespace="TUSER" > <resultMap id="BaseResultMap" class="hyl.model.Tuser" > <result column="ID" property="id" jdbcType="VARCHAR" /> <result column="NAME" property="name" jdbcType="VARCHAR" /> <result column="PWD" property="pwd" jdbcType="VARCHAR" /> <result column="CREATEDATATIME" property="createdatatime" jdbcType="DATE" /> <result column="MODIFYDATATIME" property="modifydatatime" jdbcType="DATE" /> </resultMap> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterClass="hyl.model.Tuser" > select ID, NAME, PWD, CREATEDATATIME, MODIFYDATATIME from TUSER where ID = #id:VARCHAR# </select> <delete id="deleteByPrimaryKey" parameterClass="hyl.model.Tuser" > delete from TUSER where ID = #id:VARCHAR# </delete> <insert id="insert" parameterClass="hyl.model.Tuser" > insert into TUSER (ID, NAME, PWD, CREATEDATATIME, MODIFYDATATIME) values (#id:VARCHAR#, #name:VARCHAR#, #pwd:VARCHAR#, #createdatatime:DATE#, #modifydatatime:DATE#) </insert> <insert id="insertSelective" parameterClass="hyl.model.Tuser" > insert into TUSER <dynamic prepend="(" > <isNotNull prepend="," property="id" > ID </isNotNull> <isNotNull prepend="," property="name" > NAME </isNotNull> <isNotNull prepend="," property="pwd" > PWD </isNotNull> <isNotNull prepend="," property="createdatatime" > CREATEDATATIME </isNotNull> <isNotNull prepend="," property="modifydatatime" > MODIFYDATATIME </isNotNull> ) </dynamic> values <dynamic prepend="(" > <isNotNull prepend="," property="id" > #id:VARCHAR# </isNotNull> <isNotNull prepend="," property="name" > #name:VARCHAR# </isNotNull> <isNotNull prepend="," property="pwd" > #pwd:VARCHAR# </isNotNull> <isNotNull prepend="," property="createdatatime" > #createdatatime:DATE# </isNotNull> <isNotNull prepend="," property="modifydatatime" > #modifydatatime:DATE# </isNotNull> ) </dynamic> </insert> <update id="updateByPrimaryKeySelective" parameterClass="hyl.model.Tuser" > update TUSER <dynamic prepend="set" > <isNotNull prepend="," property="name" > NAME = #name:VARCHAR# </isNotNull> <isNotNull prepend="," property="pwd" > PWD = #pwd:VARCHAR# </isNotNull> <isNotNull prepend="," property="createdatatime" > CREATEDATATIME = #createdatatime:DATE# </isNotNull> <isNotNull prepend="," property="modifydatatime" > MODIFYDATATIME = #modifydatatime:DATE# </isNotNull> </dynamic> where ID = #id:VARCHAR# </update> <update id="updateByPrimaryKey" parameterClass="hyl.model.Tuser" > update TUSER set NAME = #name:VARCHAR#, PWD = #pwd:VARCHAR#, CREATEDATATIME = #createdatatime:DATE#, MODIFYDATATIME = #modifydatatime:DATE# where ID = #id:VARCHAR# </update> </sqlMap> 这个问题困扰我一周了,希望各位能帮助下,若需要我的项目请与我联系:QQ632105841,再次谢谢!
@Async 异步失效。。。。。。。。。。。。。
我有一个切面用来管理操作日志的。代码如下 ``` ``` package com.amn.aspect; import com.amn.controller.SystemControllerLog; import com.amn.exception.AmnException; import com.amn.model.SysLog; import com.amn.service.SysLogService; import com.amn.util.DateUtil; import com.amn.util.StringUtil; import com.amn.util.TokenManager; import io.jsonwebtoken.Claims; import net.sf.json.JSONObject; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.NamedThreadLocal; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Map; @Aspect @Component public class SystemLogAspect { private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class); @Autowired(required=false) private HttpServletRequest request; @Autowired private SysLogService logService; //@Autowired //private LogService logService; /** * Controller层切点 注解拦截 */ //@Pointcut("execution(* com.amn.controller.*.*(..))") @Pointcut("@annotation(com.amn.controller.SystemControllerLog)") public void controllerAspect(){ System.out.println("fsdfssssssssssssss"); } @Before("controllerAspect()") public void doBefore(JoinPoint joinPoint) throws InterruptedException{ } public static String getControllerMethodDescription2(JoinPoint joinPoint) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); SystemControllerLog controllerLog = method .getAnnotation(SystemControllerLog.class); String discription = controllerLog.description(); return discription; } @SuppressWarnings("unchecked") @After("controllerAspect()") public void doAfter(JoinPoint joinPoint) { SysLog sysLog=getSysLog(request); String param=""; param=com.alibaba.fastjson.JSONObject.toJSONString(joinPoint.getArgs()); sysLog.setTitle(getControllerMethodDescription2(joinPoint)); sysLog.setParams(sysLog.getParams()+"请求参数:"+param); logService.saveSysLog(sysLog); //sysLog.setTimeout(DateUtils.formatDateTime(endTime - beginTime)); //threadPoolTaskExecutor.execute(new SaveLogThread(sysLog, logService)); //logThreadLocal.set(sysLog); } @AfterThrowing(pointcut = "controllerAspect()", throwing = "e") public void doAfterThrowing(JoinPoint joinPoint, Throwable e) { SysLog sysLog=getSysLog(request); sysLog.setType("error"); sysLog.setException(e.toString()); sysLog.setLogId(StringUtil.guid()); String param=""; param=com.alibaba.fastjson.JSONObject.toJSONString(joinPoint.getArgs()); sysLog.setParams(sysLog.getParams()+"请求参数:"+param); sysLog.setTitle(getControllerMethodDescription2(joinPoint)); logService.saveSysLog(sysLog); } public SysLog getSysLog(HttpServletRequest request) { String title = ""; String type = "info"; String remoteAddr = request.getRemoteAddr();//请求的IP String requestUri = request.getRequestURI();//请求的Uri String method = request.getMethod(); //请求的方法类型(post/get) String token = request.getParameter("token"); Map<String, String[]> params = request.getParameterMap(); //请求提交的参数 String operationid = ""; if (StringUtil.isEmpty(token)) { try { Claims claims = TokenManager.parseJWT(token); if (claims != null) { operationid = claims.get("jti").toString(); } } catch (Exception e) { e.printStackTrace(); } } SysLog sysLog = new SysLog(); sysLog.setLogId(StringUtil.guid()); sysLog.setTitle(title); sysLog.setType(type); sysLog.setRemoteAddr(remoteAddr); sysLog.setRequestUri(requestUri); sysLog.setMethod(method); if (params != null && params.size() > 0) { sysLog.setParams(JSONObject.fromObject(params).toString()); } sysLog.setUserId(operationid); Date operateDate = new Date(); sysLog.setOperateDate(operateDate); return sysLog; } } 然后@async 标记的方法不能异步执行了。有大神知道什么原因吗?
求大神帮忙 spring aop 方式事务不回滚怎么搞?
spring 版本 4.1.7 代码如下: 表: CREATE TABLE `users` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `nick_name` varchar(100) DEFAULT NULL, `password` varchar(100) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; INSERT INTO `users` VALUES ('1', 'Jennifer', 'Alice'); INSERT INTO `users` VALUES ('2', '爱', '克斯莱'); java 文件: 1) package com.maxwell.spring.jdbc.tx; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.maxwell.spring.jdbc.vo.User; @Service public class UserAopService { @Autowired private UserDao dao; public UserAopService() {} /** * 此处的@Transactional注解把这个方法中的所有数据库操作当作事务进行处理 */ public void testTransactionManager() { String nn = dao.addUser(new User().setNickName("Jensen").setPassword("jensen")); int i = dao.getIdByNickName(nn); System.out.println(i); dao.setNickNameById(i, "Nimei"); } } 2) package com.maxwell.spring.jdbc.tx; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; import com.maxwell.spring.jdbc.vo.User; /** * 用于测试事务 * @author Techwork * */ @Repository public class UserDao { @Autowired @Qualifier("npJdbcTpl") private NamedParameterJdbcTemplate jdbcTpl; public String addUser(User user) { String sql = "INSERT INTO users (nick_name, password) VALUES (:nickName, :password)"; SqlParameterSource paramSource = new BeanPropertySqlParameterSource(user); jdbcTpl.update(sql, paramSource); return user.getNickName(); } public int getIdByNickName(String nickName) { String sql = "select id, nick_name, password from users where nick_name = :xxx"; Map<String, Object> paramMap = new HashMap<>(); paramMap.put("xxx", nickName); RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class); List<User> users = jdbcTpl.query(sql, paramMap, rowMapper); if(users == null || users.size() < 1) { throw new RuntimeException("无此用户:" + nickName); } return users.get(0).getId(); } public void setNickNameById(int id, String nickName) { if(nickName.length() < 10) throw new RuntimeException("性别错误"); String sql = "update users set nick_name = :n where id = :i"; Map<String, Object> paramMap = new HashMap<>(); paramMap.put("n", nickName); paramMap.put("i", id); jdbcTpl.update(sql, paramMap); } } 3) package com.maxwell.spring.jdbc.tx; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import com.maxwell.spring.jdbc.vo.User; @Service public class UserService { @Autowired private UserDao dao; public UserService() {} /** * 此处的@Transactional注解把这个方法中的所有数据库操作当作事务进行处理 */ @Transactional public void testTransactionManager() { String nn = dao.addUser(new User().setNickName("Jensen").setPassword("jensen")); int i = dao.getIdByNickName(nn); System.out.println(i); dao.setNickNameById(i, "Nimei"); } /** * propagation: 指定事务的传播行为 * isolation: 指定事务的隔离级别 * noRollbackFor: 指定对哪些异常不回滚。通常取默认值。 * rollbackFor: 指定对哪些异常回滚。通常取默认值。 * readOnly: 只读事务。如果事务只读取数据,而不写数据的话,设置为true,有助于数据库引擎优化事务。 * timeout: 指定强制回滚事务(就算可能成功)之前,事务可以存在的时间,以防止事务占用数据库连接时间过长。 */ @Transactional(isolation = Isolation.READ_COMMITTED, noRollbackFor = { Exception.class }, rollbackFor = { RuntimeException.class }, readOnly = true, timeout = 3) public void testTransactionManager2() { String nn = dao.addUser(new User().setNickName("Jensen").setPassword("jensen")); int i = dao.getIdByNickName(nn); dao.setNickNameById(i, "哈哈"); } } 4) package com.maxwell.spring.jdbc; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.maxwell.spring.jdbc.tx.UserAopService; /** * 测试AOP事务 * * @author Angrynut * */ public class AOPTransactionTest { private ApplicationContext ctx = null; private UserAopService service = null; { ctx = new ClassPathXmlApplicationContext("aoptx.xml"); service = ctx.getBean("userAopService", UserAopService.class); } /** * 1.测试AOP事务。 */ @Test public void testTransactionManager() { service.testTransactionManager(); } } 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:util="http://www.springframework.org/schema/util" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd"> <context:component-scan base-package="com.maxwell.spring.jdbc"/> <!-- 数据源配置文件 --> <util:properties id="db" location="classpath:db.properties"/> <!-- 配置C3p0数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="#{db['jdbc.user']}"/> <property name="password" value="#{db['jdbc.password']}"/> <property name="driverClass" value="#{db['jdbc.driverClass']}"/> <property name="jdbcUrl" value="#{db['jdbc.jdbcUrl']}"/> <property name="initialPoolSize" value="#{db['jdbc.initPoolSize']}"/> <property name="maxPoolSize" value="#{db['jdbc.maxPoolSize']}"/> </bean> <bean id="npJdbcTpl" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"> <constructor-arg ref="dataSource"/> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.maxwell.spring.jdbc.tx.UserService.*(..))" id="pc"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/> </aop:config> </beans>
struts2.3spring4.1hibernate4.3的集成问题
Error configuring application listener of class org.springframework.web.util.Log4jConfigListener java.lang.ClassNotFoundException: org.springframework.web.util.Log4jConfigListener Error configuring application listener of class org.springframework.web.context.ContextLoaderListener java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener Error configuring application listener of class org.springframework.web.context.request.RequestContextListener java.lang.ClassNotFoundException: org.springframework.web.context.request.RequestContextListener spring-web放在WEB-INF/lib下路径是问题的,不知道哪里出错 ``` <?xml version="1.0" encoding="UTF-8"?> <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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>S2316S411H436</display-name> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>struts2Filter</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>hibernate4Filter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>hibernate4Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app> ``` ``` <?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:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 说明:下面有的Bean配置提供了多种方案,请根据需要采用某一种(别忘了注释掉其他同类方案) --> <!-- 自动扫描Spring注解配置 --> <context:component-scan base-package="com" /> <!-- 自动加载属性配置文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 配置数据源:方法一,使用C3P0方式(推荐) --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" p:driverClass="${jdbc.driverClassName}" p:jdbcUrl="${jdbc.url}" p:user="${jdbc.username}" p:password="${jdbc.password}" /> <!-- 配置数据源:方法二,使用DBCP方式(不推荐) --> <!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> --> <!-- 配置数据源:方法三,使用JNDI方式 --> <!-- <jee:jndi-lookup id="dataSource" jndi-name="${jndi.name}" /> --> <!-- 配置Hibernate的数据源代理工厂:方法一,使用p属性通配符,按文件名搜索匹配的映射文件 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:mappingLocations="classpath*:/com/**/*.hbm.xml"> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> </props> </property> </bean> <!-- 配置Hibernate的数据源代理工厂:方法二,使用list集合,按文件名搜索匹配的映射文件 --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource"> <property name="mappingLocations"> <list> <value>classpath*:/com/**/*.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> </props> </property> </bean> --> <!-- 配置Hibernate的数据源代理工厂:方法三,使用p属性通配符,按目录搜索映射文件 --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:mappingDirectoryLocations="classpath*:/com/**/domain"> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> </props> </property> </bean> --> <!-- 配置Hibernate的数据源代理工厂:方法四,使用hibernate.cfg.xml --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:hibernate.cfg.xml"> </bean> --> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" /> <!-- 配置声明式事务:方法一,在Service实现类或者public实现方法上使用注解@Transactional,则此类或方法就会启用事务机制 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 配置声明式事务:方法二,使用tx/aop命名空间的配置(其实还有方法三,由于快要过时不推荐使用了,这里就不给出方法三的配置了) --> <!-- <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="new*" propagation="REQUIRED" /> <tx:method name="set*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="change*" propagation="REQUIRED" /> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="load*" propagation="REQUIRED" read-only="true" /> <tx:method name="search*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" read-only="true" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="mypointcut" expression="execution(* com.**.service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="mypointcut" /> </aop:config> --> <!-- 下面三个Bean的配置可有可无,但配置后用处更大,通常用于BaseDao类、其他Dao类或特殊工具类中 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate" p:sessionFactory-ref="sessionFactory" /> <bean id="hibernateDaoSupport" class="org.springframework.orm.hibernate4.support.HibernateDaoSupport" p:hibernateTemplate-ref="hibernateTemplate" abstract="true"/> <bean id="sessionFactoryUtils" class="org.springframework.orm.hibernate4.SessionFactoryUtils" abstract="true"/> </beans> ```
使用maven搭建的ssm框架能够访问jsp页面但是就是无法访问controller层,代码如下
controller层是这样的 @Controller @RequestMapping("web_User") public class UserController { private static final Logger logger = Logger.getLogger(UserController.class); @Resource private UserService userService; /** * 获取具体用户信息 * */ @RequestMapping(value = { "getUserById_test" }, method = { RequestMethod.POST }) public @ResponseBody Map<String,Object> getVideoById(@RequestParam long id) { User user = userService.finduserById(id); Map<String, Object> map = new HashMap<String, Object>(); map.put("result", user); return map; } } applicationcontext是这样的 <?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:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd "> <mvc:annotation-driven /> <context:annotation-config /> <mvc:default-servlet-handler /> <context:component-scan base-package="com.gp.demo.*" /> <!-- 启用缓存注解功能 --> <cache:annotation-driven cache-manager="cacheManager"/> <!-- 缓存管理器工厂加载ehcache的配置 --> <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation" value="classpath:ehcache.xml"/> </bean> <!-- 声明缓存管理器 --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="cacheManagerFactory"/> </bean> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:jdbc.properties</value> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan"> <list> <value>com.gp.demo.domain</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="initialSize" value="${jdbc.initialSize}" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="dataSource" ref="dataSource" /> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <!-- 连接事务的注解配置 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 配置事务的传播特性 hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="Find*" propagation="REQUIRED" read-only="true" /> <tx:method name="is*" propagation="REQUIRED" read-only="true" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="send*" propagation="REQUIRED" /> <tx:method name="accept*" propagation="REQUIRED" /> <tx:method name="approve*" propagation="REQUIRED" /> <tx:method name="count*" propagation="REQUIRED" /> <tx:method name="sort*" propagation="REQUIRED" /> <tx:method name="set*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="merge*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="put*" propagation="REQUIRED" /> <tx:method name="use*" propagation="REQUIRED" /> <tx:method name="register*" propagation="REQUIRED" /> <tx:method name="search*" propagation="REQUIRED" /> <tx:method name="get*" propagation="REQUIRED" /> <tx:method name="cancel*" propagation="REQUIRED" /> <tx:method name="login*" propagation="REQUIRED" read-only="true" /> <tx:method name="count*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="list*" propagation="REQUIRED" read-only="true" /> <!-- <tx:method name="*" read-only="true" /> --> </tx:attributes> </tx:advice> <!-- 那些类的哪些方法参与事务 --> <aop:config> <aop:pointcut id="allManagerMethod" expression="execution(public * com.gp.demo.service.*.*(..))" /> <aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice" /> </aop:config> <mvc:annotation-driven /> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" /> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" /> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="order" value="0" /> <property name="cacheSeconds" value="0" /> <property name="webBindingInitializer"> <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> </bean> </property> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" /> <bean class="org.springframework.http.converter.StringHttpMessageConverter" /> <bean class="org.springframework.http.converter.FormHttpMessageConverter" /> <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter" /> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> </list> </property> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 定时邮件 --> <!-- end 定时邮件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置上传文件的最大尺寸为100MB --> <property name="maxUploadSize"> <value>104857600</value> </property> </bean> <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException --> <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 --> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 --> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop> </props> </property> </bean> <!-- <bean id="Obtainemile" class="com.wiwoworld.oa.web.NoticeController.Obtainemile" scope="singleton" init-method="startThread"></bean> <bean id="affordVisit" class="com.xmpp.manager.MangerThread.visitDatabase" scope="singleton" init-method="startThread"></bean> --> <!-- <bean id="lunxunqidong" class="com.wiwoworld.oa.web.NoticeController" scope="singleton" init-method="searchMailnotice"></bean> --> </beans>
SSH整合框架中save方法执行的时候会删除原有数据
SSH整合框架中save方法执行的时候会删除原有数据 如: Hibernate: delete from stu_tea where tea_id=? Hibernate: insert into stu_tea (tea_id, stu_id) values (?, ?) 我用的实体类注解方式,多对多关联关系,学生和老师类,执行save的时候每次中间表的关联关系都会被新的关联关系覆盖,看sql语句输出是现实先把原来的删除了,再添加的,检查过自己的配置<prop key="hibernate.hbm2ddl.auto">update</prop>这个确定是update不是create; ## 学生类 ``` package com.cdd.ssh.entity; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; @Entity public class Students { @Id @Column(name="sId")//可省略 //设置主键自增 @GeneratedValue(strategy = GenerationType.AUTO) private int sId; private String sName; private String sSex; private int sAge; @ManyToMany(mappedBy="students",cascade={CascadeType.PERSIST}) private Set<Teachers> teachers = new HashSet<Teachers>(); public int getsId() { return sId; } public void setsId(int sId) { this.sId = sId; } public String getsName() { return sName; } public void setsName(String sName) { this.sName = sName; } public String getsSex() { return sSex; } public void setsSex(String sSex) { this.sSex = sSex; } public int getsAge() { return sAge; } public void setsAge(int sAge) { this.sAge = sAge; } public Set<Teachers> getTeachers() { return teachers; } public void setTeachers(Set<Teachers> teachers) { this.teachers = teachers; }; } ``` ## 老师类 ``` package com.cdd.ssh.entity; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity //注明实体类对应表明,省略默认使用类名 @Table(name="teachers") public class Teachers { //表明id列 @Id @Column(name="tId")//可省略 //设置主键自增 @GeneratedValue(strategy = GenerationType.AUTO) private int tId; private String tType;//科目 private String tName;//姓名 @ManyToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE}) //设置中间表关联关系 @JoinTable(name="stu_tea", joinColumns ={@JoinColumn(name = "tea_id")}, inverseJoinColumns={@JoinColumn(name="stu_id")}) private Set<Students> students = new HashSet<Students>(); public int gettId() { return tId; } public void settId(int tId) { this.tId = tId; } public String gettType() { return tType; } public void settType(String tType) { this.tType = tType; } public String gettName() { return tName; } public void settName(String tName) { this.tName = tName; } public Set<Students> getStudents() { return students; } public void setStudents(Set<Students> students) { this.students = students; } } ``` ## 这个是dao中的执行方法 ``` public void add(Students student, Teachers teacher) { // TODO Auto-generated method stub Session session = this.getSession(); student.getTeachers().add(teacher); teacher.getStudents().add(student); session.save(teacher); session.save(student); System.out.println(teacher.gettId()); System.out.println(student.getsId()); } ``` 这是我的代码,求大神帮忙啊,一下午了都没弄好, 在这之前我是写的学生和教室类,后来感觉教室不合适,就把教室改成老师类了,配置文件和属性都没有改变,只把用到教室的地方换成了老师; 求大神帮忙 ## 这里是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: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-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd "> <!-- 开启注解 --> <context:annotation-config/> <!-- 扫描包设置 --> <context:component-scan base-package="com.cdd.ssh.*"></context:component-scan> <!--DateSource数据源 使用DBCP连接池--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/school?useUnicode=true&amp;characterEncoding=UTF8"/> <property name="username" value="root"/> <property name="password" value="chengzi"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!-- 载入实体类 mappingResources --> <property name="packagesToScan"> <value>com.cdd.ssh.entity</value> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <!-- 3.~~~~~~~~~~~~~~~~~~~~~~~~~事务配置~~~~~~~~~~~~~~~~~~~~~~~~~~~~--> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" > <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="txManager" /> <aop:config> <aop:pointcut expression="execution(public * com.cdd.ssh.service.*.*(..))" id="bussinessService"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="bussinessService" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="txManager" > <tx:attributes> <tx:method name="query*" read-only="true" propagation="NOT_SUPPORTED" /> <!-- get开头的方法不需要在事务中运行 。 有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的--> <tx:method name="*"/> <!-- 其他方法在实务中运行 --> </tx:attributes> </tx:advice> </beans> ```
动态切换数据源不能正常切换
在开发双数据源按需切换的时候,发现不能按要求切换数据源。环境是:struts2、spring、Hibernate。源代码如下: 数据源设置类: ``` public class DataSourceSwitcher { public static final String DATA_SOURCE_MASTER = "master"; // 主库 public static final String DATA_SOURCE_SLAVE = "slave"; // 从库 private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); /** * 设置数据源 */ public static void setDataSource(String dbName) { contextHolder.set(dbName); } /** * 获取数据源 */ public static String getDataSource() { return (String) contextHolder.get(); } /** * 删除数据源 */ public static void removeDataSource() { contextHolder.remove(); } } ``` 动态切换类: ``` public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { System.out.println("切换数据源到:" + DataSourceSwitcher.getDataSource()); return DataSourceSwitcher.getDataSource(); } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } } ``` AOP切面类: ``` @Component @Aspect @Order(0) public class DataSourceAdvice { private static Logger logger = Logger.getLogger(DataSourceAdvice.class); @Before(("@annotation(com.common.DynamicDataSourceAnnotation)")) public void before(JoinPoint point) { try { // 获取数据源 String dataSource = getDataSource(point); // 设置数据源 logger.info("设置数据源" + dataSource); DataSourceSwitcher.setDataSource(dataSource); } catch (Exception e) { logger.error("设置数据源失败..."); logger.error(StringHandleUtils.getExceptionInfo(e)); } } @After("@annotation(com.common.DynamicDataSourceAnnotation)") //后置通知 public void testAfter(JoinPoint point){ try { // 获取数据源 String dataSource = getDataSource(point); // 若数据源不是主库,则清空 if(!DataSourceSwitcher.DATA_SOURCE_MASTER.equals(dataSource)) { logger.error("删除数据源" + dataSource + "成功..."); DataSourceSwitcher.removeDataSource(); } } catch (Exception e) { logger.error("删除数据源失败..."); logger.error(StringHandleUtils.getExceptionInfo(e)); } } @SuppressWarnings("rawtypes") private String getDataSource(JoinPoint point) { String dataSource = DataSourceSwitcher.DATA_SOURCE_MASTER; try{ Class<?> className = point.getTarget().getClass(); String methodName = point.getSignature().getName(); Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes(); Method method = className.getMethod(methodName, argClass); if (method.isAnnotationPresent(DynamicDataSourceAnnotation.class)) { DynamicDataSourceAnnotation annotation = method.getAnnotation(DynamicDataSourceAnnotation.class); dataSource = annotation.dataSource(); } }catch(Exception e) { logger.error("获取数据源失败..."); logger.error(StringHandleUtils.getExceptionInfo(e)); } return dataSource; } } ``` 注解类: ``` @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface DynamicDataSourceAnnotation { String dataSource() default DataSourceSwitcher.DATA_SOURCE_MASTER; } ``` 配置文件: ``` <!-- master --> <bean id="master" class="com.common.DataSource"> <property name="driver" value="${master.datasource.driverClassName}" /> <property name="driverUrl" value="${master.datasource.url}" /> <property name="user" value="${master.datasource.username}"/> <property name="password" value="${master.datasource.password}"/> <property name="alias" value="master" /> </bean> <!-- slave --> <bean id="slave" class="com.common.DataSource"> <property name="driver" value="${slave.datasource.driverClassName}" /> <property name="driverUrl" value="${slave.datasource.url}" /> <property name="user" value="${slave.datasource.username}"/> <property name="password" value="${slave.datasource.password}"/> <property name="alias" value="slave" /> </bean> <!-- 配置动态切换数据源 --> <bean id="dataSource" class="com.common.DynamicDataSource"> <property name="defaultTargetDataSource" ref="master"></property> <property name="targetDataSources"> <map key-type="java.lang.Object"> <entry value-ref="master" key="master"></entry> <entry value-ref="slave" key="slave"></entry> </map> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> </props> </property> <property name="packagesToScan" value="com.common.pojo"/> </bean> <!-- 定义事务管理器(声明式的事务) --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <aop:aspectj-autoproxy proxy-target-class="true" /> <tx:annotation-driven transaction-manager="transactionManager" /> ``` 使用: Action层: ``` @Action(name = "common") @Component public class CommonAction extends ActionSupport{ @Autowired private CommonService service; public String queryInfo() { List<TradeInfo> list = service.queryInfo(); for(TradeInfo ti : list) { System.out.println("service.queryInfo():" + ti.getName()); } System.out.println("================================"); List<TradeInfo> list2 = service.queryInfo2(); for(TradeInfo ti : list2) { System.out.println("service.queryInfo2():" + ti.getName()); } return "index"; } } ``` Service层: ``` @Service @Transactional(rollbackFor = Exception.class) public class CommonService { @Autowired private CommonDAO commonDAO; @SuppressWarnings("unchecked") @Override @DynamicDataSourceAnnotation(dataSource = DataSourceSwitcher.DATA_SOURCE_MASTER) public List<TradeInfo> queryInfo() throws SystemException { try { String sql = "FROM TradeInfo"; return this.commonDAO.find(sql); } catch (Exception e) { } } @SuppressWarnings("unchecked") @Override @DynamicDataSourceAnnotation(dataSource = DataSourceSwitcher.DATA_SOURCE_SLAVE) public List<TradeInfo> queryInfo2() throws SystemException { try { String sql = "FROM TradeInfo"; return this.commonDAO.find(sql); } catch (Exception e) { } } } ``` Dao层: ``` @Repository public class CommonDao extends HibernateDaoSupport { public List find(String sql) throws SystemException { try { return getHibernateTemplate().find(sql); } catch (DataAccessException e) { } catch (HibernateException e) { } catch (SQLException e) { } return null; } } ``` 测试输出结果: ``` 设置数据源master 切换数据源到:master 删除数据源master成功... service.queryInfo():主数据源 ================================ 设置数据源slave 切换数据源到:slave service.queryInfo()2:主数据源 ``` 从输出信息可以看出数据源并没有成功切换。queryInfo()走的是主数据源;queryInfo()2走的也是主数据源。 调试结果是:第一个方法可以正常切换数据源,第一个方法之后的方法都无法正常切换,获取的连接是第一个方法的连接。 而在Action中用Main方法: ``` public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); CommonAction = (CommonAction ) ctx.getBean("commonAction"); c.queryInfo(); ) ``` 输出结果: ``` 设置数据源master 切换数据源到:master 切换数据源到:master 删除数据源master成功... service.queryInfo():主数据源 ================================ 设置数据源slave 切换数据源到:slave 切换数据源到:slave service.queryInfo()2:从数据源 ``` 从输出信息可以看出数据源按照预期正常切换了。 请问出现这种问题有哪些可能因素影响呢?
spring2.5.6 配置 openJpa 异常
最近在做一个小列子,原本是用配置文件方式注入的,之后我想改为用注解的方式注入,问题就出现了。 错误代码如下: [code="java"]2010-2-4 22:18:04 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet default threw exception java.lang.IllegalArgumentException: entityManagerFactory or jpaTemplate is required at org.springframework.orm.jpa.support.JpaDaoSupport.checkDaoConfig(JpaDaoSupport.java:119) at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:671) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:610) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:499) at org.springframework.beans.factory.annotation.InjectionMetadata.injectMethods(InjectionMetadata.java:117) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:253) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:998) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:671) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:610) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType(AbstractAutowireCapableBeanFactory.java:1076) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:982) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:329) at com.opensymphony.xwork2.spring.SpringObjectFactory.autoWireBean(SpringObjectFactory.java:168) at com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:155) at com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:129) at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:143) at com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:113) at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:275) at com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:365) at com.opensymphony.xwork2.DefaultActionInvocation.access$000(DefaultActionInvocation.java:38) at com.opensymphony.xwork2.DefaultActionInvocation$1.doProfiling(DefaultActionInvocation.java:83) at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455) at com.opensymphony.xwork2.DefaultActionInvocation.<init>(DefaultActionInvocation.java:74) at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:189) at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:41)[code="java"][/code] at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:494) at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619)[/code] java代码如下: [code="java"] @Repository public class ExamDAOImpl extends JpaDaoSupport implements ExamDAO{ private String hql = "from Exam a "; //新增试卷 public void create(Exam exam) { this.getJpaTemplate().persist(exam); } //修改试卷 public void update(Exam exam) { this.getJpaTemplate().merge(exam); } //删除试卷 public void delete(Exam exam) { this.getJpaTemplate().remove(this.getJpaTemplate().merge(exam)); } //根据id获取试卷信息 public Exam query(int id) { Exam exam = this.getJpaTemplate().find(Exam.class, id); return exam; } //获取所有试卷的信息 @SuppressWarnings("unchecked") public List<Exam> queryList() { List<Exam> list = new ArrayList<Exam>(); list = this.getJpaTemplate().find(hql); return list; } } @Namespace("/") @Results({@Result("jsp/examManagement.jsp"), @Result(name="createQuestion", value = "jsp/questionManagement.jsp"), @Result(name="exam", value = "jsp/exam.jsp"), @Result(name="examResult", value = "jsp/examResult.jsp")}) public class ExamAction extends ActionSupport { private static final long serialVersionUID = 5192939935859483841L; //新增试卷信息 public String create() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); //进行新增 getExamService().create(exam); //获取已有的试卷信息 List<Exam> listExams = getExamService().queryList(); //将已有的试卷信息传递给页面 req.setAttribute("listExams", listExams); //存放消息 req.setAttribute("msg", "新增成功"); return SUCCESS; } //修改试卷信息 public String update() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); //进行修改 getExamService().update(exam); //获取已有的试卷信息 List<Exam> listExams = getExamService().queryList(); //将已有的试卷信息传递给页面 req.setAttribute("listExams", listExams); //存放消息 req.setAttribute("msg", "修改成功"); return SUCCESS; } //删除试卷信息 public String delete() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); //进行删除 getExamService().delete(exam); //获取已有的试卷信息 List<Exam> listExams = getExamService().queryList(); //将已有的试卷信息传递给页面 req.setAttribute("listExams", listExams); //存放消息 req.setAttribute("msg", "删除成功"); return SUCCESS; } //设定该试卷下的题目 public String createQuestion() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); exam = getExamService().query(exam.getId()); //获取该试卷题目下已有的题目 Set<Question> listQuestions = exam.getQuestion(); //将该试卷题目下已有的题目信息传递给页面 req.setAttribute("listQuestions", listQuestions); //将该试卷信息传递给页面 req.setAttribute("exam", exam); //存放消息 req.setAttribute("msg", "欢迎进入" + exam.getName() + "试题题目管理系统"); return "createQuestion"; } //进行考试 public String exam() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); //获取试卷信息 Exam exam = getExamBean(req, res); exam = getExamService().query(exam.getId()); //将该试卷信息传递给页面 req.setAttribute("exam", exam); //存放消息 req.setAttribute("msg", "欢迎您开始《" + exam.getName() + "》试卷"); return "exam"; } //统计试卷成绩 public String submitExam() { HttpServletRequest req = ServletActionContext.getRequest(); //获取试卷信息 Exam exam = new Exam(); exam = getExamService().query(Integer.valueOf(req.getParameter("examId"))); //定义该此考试的分数 float result = 0f; //获取该试卷下的题目 Set<Question> listQuestions = exam.getQuestion(); Iterator<Question> iterator = listQuestions.iterator(); //获取每个题目下的项目 while (iterator != null && iterator.hasNext()) { Question question = (Question)iterator.next(); //获取该题目下的项目 List<QuestionItem> listQuestionItems = question.getQuestionItem(); //获取用户选择的题目下的项目 Assert.notNull((String)req.getParameter(question.getId() + "")); int questionId = Integer.valueOf((String)req.getParameter(question.getId() + "")); //累计用户提交的题目下的项目 for (int j = 0; listQuestionItems != null && j < listQuestionItems.size(); j++) { QuestionItem questionItem = (QuestionItem)listQuestionItems.get(j); if(questionId == questionItem.getId()) { if (questionItem.getIsOk() == 1) { //统计成绩 result = result + question.getPoint(); break; } } } } //将该试卷信息传递给页面 req.setAttribute("exam", exam); //将成绩传递给页面 req.setAttribute("result", result); //存放消息 req.setAttribute("msg", "欢迎您查看《" + exam.getName() + "》试卷的成绩"); return "examResult"; } public String index() { HttpServletRequest req = ServletActionContext.getRequest(); //获取已有的试卷信息 List<Exam> listExams = getExamService().queryList(); //将已有的试卷信息传递给页面 //System.out.println("listExams.size==="+listExams.size()); req.setAttribute("listExams", listExams); req.setAttribute("msg", "欢迎进入试卷题目管理系统"); return SUCCESS; } //获取试卷业务逻辑 public ExamService getExamService(){ return examService; } //设定试卷业务逻辑 @Autowired public void setExamService(ExamService examService){ this.examService = examService; } private ExamService examService; //获取试题项目业务逻辑 public QuestionItemService getQuestionItemService(){ return questionItemService; } //设定试题项目业务逻辑 @Autowired public void setQuestionItemService(QuestionItemService questionItemService){ this.questionItemService = questionItemService; } private QuestionItemService questionItemService; //封装试卷基本信息 public Exam getExamBean(HttpServletRequest req, HttpServletResponse res) { Exam exam = new Exam(); try { //判断是否是新增或者修改还是删除,如果是新增则不需要id String hh = req.getParameter("examId" + (String)req.getParameter("checkbox") + ""); if (!"".equals(hh) && hh != null) { exam.setId(Integer.valueOf(req.getParameter("examId" + (String)req.getParameter("checkbox") + ""))); } //获取基本信息 exam.setName(((String)req.getParameter("name" + (String)req.getParameter("checkbox") + ""))); } catch (Exception ex) { ex.printStackTrace(); } return exam; } } [/code] struts和spring的配置文件如下: [code="java"] <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!--表示可以使用动态方法调用,即userAction!delete.action的形式--> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <!--表示struts处于开发状态--> <constant name="struts.devMode" value="true" /> <constant name="struts.convention.classes.reload" value="true" /> <constant name="struts.objectFactory.spring.autoWire" value="type" /> <!--使用默认的命名空间、即根目录/,在访问的时候,直接http://localhost:8080/webExam/userAction!delete.action--> <!--<package name="default" extends="struts-default"> 定义动态方法调用examAction!*.action <action name="examAction" class="examAction"> <result>jsp/examManagement.jsp</result> <result name="createQuestion">jsp/questionManagement.jsp</result> <result name="exam">jsp/exam.jsp</result> <result name="examResult">jsp/examResult.jsp</result> </action> 定义动态方法调用questionAction!*.action <action name="questionAction" class="questionAction"> <result>jsp/questionManagement.jsp</result> <result name="createItem">jsp/questionItemManagement.jsp</result> </action> 定义动态方法调用questionItemAction!*.action <action name="questionItemAction" class="questionItemAction"> <result>jsp/questionItemManagement.jsp</result> </action> </package>--> </struts> <?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:jee="http://www.springframework.org/schema/jee" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:http-conf="http://cxf.apache.org/transports/http/configuration" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" default-lazy-init="true"> <context:component-scan base-package="com.webExam.dao.impl,com.webExam.service.impl"/> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="entityManager"/> <property name="jpaProperties"> <props></props> </property> </bean> </beans> [/code] persistence文件如下: [code="java"]<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <!--定义持久单元--> <persistence-unit name="entityManager" transaction-type="RESOURCE_LOCAL"> <!--这里采用Hibernate提供的持久化类--> <provider>org.hibernate.ejb.HibernatePersistence</provider> <!--定义持久化属性--> <properties> <!--定义方言、fetch深度、是否显示sql--> <property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect" /> <property name="hibernate.max_fetch_depth" value="3" /> <property name="hibernate.show_sql" value="true" /> <!--定义是否自动生成表,create表示每次加载都重新生成,update表示每次加载只是更新表--> <property name="hibernate.hbm2ddl.auto" value="update" /> <!--定义数据库连接的相关属性--> <property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver" /> <property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:FLOW" /> <!--定义数据库连接的用户名、密码等--> <property name="hibernate.connection.username" value="arch" /> <property name="hibernate.connection.password" value="arch" /> </properties> </persistence-unit> </persistence>[/code]
Spring2.5事务管理没有运行起来,哪里错了咧?
基于泛型、反射,使用jdbcTemplate写了一个公共DAO,作为小例子前提测试一下业务层的事务,用的注解@Transactional DAO代码片断: [code="java"] public <T> boolean insertSingleData(final List<T> datas) throws Exception{ if (null == datas || datas.size()==0) return false; ... String sql = String.format("INSERT INTO %s %s VALUES %s", type.getSimpleName().toLowerCase(), fieldList.toString().replace('[', '(').replace(']', ')'), paramList.toString().replace('[', '(').replace(']', ')') ); BatchPreparedStatementSetter setter = new BatchPreparedStatementSetter() { public void setValues(PreparedStatement arg0, int arg1) throws SQLException { final T currentVo = datas.get(arg1); for(int v=0;v<targetFields.size();v++){ try { arg0.setObject(v+1, getBeanFieldValues(currentVo,targetFields.get(v).toLowerCase())); } catch (Exception e) { e.printStackTrace(); } } } public int getBatchSize() { return datas.size(); } }; int[] result = jdbcTemplate.batchUpdate(sql, setter); return (result.length == datas.size())?true:false; } [/code] 然后有一个业务层Services的方法片段 [code="java"] @Transactional(rollbackFor=Exception.class) public void TestTrans() throws Exception{ vo =xxx; pvo = xxxx; commonDbService.insertSingleData(vo); commonDbService.insertSingleData(pvo); } [/code] pvo我模拟插入一个超长字段值,引起了异常。预期结果应该是两个都要回滚,可是vo的值却插入到数据库中了,并没有回滚? 哪里有问题咧? [b]问题补充:[/b] To:lovewhzq 是基于注解的方式 <tx:annotation-driven transaction-manager="txManager" /> 想法是在业务层实现事务控制,DAO只是最小的数据处理单元,我在业务层做的事务定义 @Transactional(rollbackFor=Exception.class) public void TestTrans() throws Exception 至于Dao这一层,做不做以下配置 @Transactional(propagation=Propagation.REQUIRED) 都不起作用,一次insertSingleData还是一个事务,二个一起跑第二个错了第一个没有回滚... [b]问题补充:[/b] 感谢各位 ========= TO:sunlightcs DAO里面没有用@Trans...只在业务层使用了。 =========== To:lovewhzq: DAO只是做了一个反射,使用的jdbcTemplate,本身并没有使用与事务相关的东东 实在很郁闷... [b]问题补充:[/b] 贴出源代码,以更新举例吧 [quote] /** * 根据主键ID更新 */ public <T> int updateDataById(T vo) throws RuntimeException{ try{ final Class<?> type = vo.getClass(); String fieldName = ""; ArrayList<String> fieldList = new ArrayList<String>(); ArrayList<String> fieldNames = new ArrayList<String>(); for(Field field : type.getDeclaredFields()){ fieldName = field.getName(); //结果值不为null并且字段名称不以_结束,即虚字段 if (null!=getBeanFieldValues(vo,fieldName) && !fieldName.endsWith("_")){ fieldList.add(fieldName.concat("=?")); fieldNames.add(fieldName); } } String sql = String.format("UPDATE %s SET %s WHERE id=?", type.getSimpleName().toLowerCase(), fieldList.toString().replace('[', ' ').replace(']', ' ') ); showLog(sql); Object[] params = new Object[fieldNames.size()+1]; for(int m=0;m<fieldNames.size();m++){ params[m] = getBeanFieldValues(vo, fieldNames.get(m)); } params[params.length-1] = getBeanFieldValues(vo, "id"); return jt.update(sql, params); }catch (Exception e){ throw new RuntimeException(); } } [/quote] 业务层测试源代码 [code="java"] @Transactional public void TestTrans() throws RuntimeException{ Person vo=null; Products pvo = null; try{ vo = commonDbService.queryDataById(Person.class, null, null, "101",null); vo.setName("aaa"); pvo = commonDbService.queryDataById(Products.class, null, null, 1, null); pvo.setProductname("jackjackjackjackjackjackjackjackjackjackjackjackjackjackjackjackjackjack");//这里引发异常 commonDbService.updateDataById(vo); // 他居然提交了,没有回滚 commonDbService.updateDataById(pvo); }catch (Exception e){ throw new RuntimeException(){}; } } [/code] Spring配置 [code="java"] <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:annotation-driven transaction-manager="txManager" /> <bean id="mainbean" class="net.duoer.MainBean" autowire="byName" /> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean> <bean id="commonDbService" class="net.duoer.service.impl.MySQLCommonDBServiceImpl"> <property name="jt" ref="jdbcTemplate" /> <property name="isDebug" value="true"></property> </bean> [/code] 不晓得哪里出了问题...
SpringMVC程序中的IllegalArgumentException
http://blog.csdn.net/sujiangchichu/article/details/16962231 抛出的的异常: [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 严重: Servlet.service() for servlet baobaotao threw exception java.lang.IllegalArgumentException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:65) at org.hibernate.tuple.entity.AbstractEntityTuplizer.setPropertyValues(AbstractEntityTuplizer.java:707) at org.hibernate.tuple.entity.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:371) at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:4295) at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:186) at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:134) at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:995) at org.hibernate.loader.Loader.doQuery(Loader.java:874) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:289) at org.hibernate.loader.Loader.doList(Loader.java:2438) at org.hibernate.loader.Loader.doList(Loader.java:2424) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2254) at org.hibernate.loader.Loader.list(Loader.java:2249) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355) at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195) at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1248) at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101) at com.baobaotao.dao.UserDao.findUserByUserName(UserDao.java:34) at com.baobaotao.service.UserService.findUserByUserName(UserService.java:22) at com.baobaotao.web.LoginController.loginCheck(LoginController.java:35) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:567) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454) at java.lang.Thread.run(Thread.java:662) [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 User.dao: [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 package com.baobaotao.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Transaction; import org.springframework.stereotype.Repository; import com.baobaotao.domain.User; @Repository //通过spring注解定义一个dao public class UserDao extends BaseDAO{ public int getMatchCount(String userName, String passWord){ String hql = "from User user " + " where user.userName = ? " + " and user.passWord = ? " ; Query queryObject = getSession().createQuery(hql); queryObject.setParameter(0,userName ); queryObject.setParameter(1, passWord); @SuppressWarnings("unchecked") List <User> list=queryObject.list(); return list.size(); } public User findUserByUserName(final String userName) { String hql = "from User user " + " where user.userName = ? "; Query queryObject = getSession().createQuery(hql); queryObject.setParameter(0,userName); User user=(User)queryObject.list().get(0); System.out.println(user); return user ; } public void updateLoginInfo(User user) { Transaction ts=getSession().beginTransaction(); getSession().update(user); ts.commit(); } } LoginController [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 package com.baobaotao.web; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.baobaotao.domain.User; import com.baobaotao.service.UserService; //标注一个springmvc的Controller @Controller public class LoginController { @Autowired private UserService userService; //负责处理index.html的请求 @RequestMapping(value="/index.html") public String loginPage(){ return "login"; } //负责处理loginCheck.html的请求 @RequestMapping(value="/loginCheck.html") public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand){ boolean isValidUser = userService.hasMatchUser(loginCommand.getUserName(),loginCommand.getPassword() ); if (!isValidUser) { return new ModelAndView("login", "error", "用户名或密码错误。"); } else { User user = userService.findUserByUserName(loginCommand.getUserName()); user.setLastIp(request.getLocalAddr()); System.out.println(request.getLocalAddr()); user.setLastVisit(new Date()); System.out.println(new Date()); userService.loginSuccess(user); // request.getSession().setAttribute("user", user); // return new ModelAndView("main"); ModelAndView mv = new ModelAndView(); mv.setViewName("main"); mv.addObject(user); return mv; } } } UserService [java] view plaincopyprint?在CODE上查看代码片派生到我的代码片 package com.baobaotao.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.baobaotao.dao.LoginLogDao; import com.baobaotao.dao.UserDao; import com.baobaotao.domain.LoginLog; import com.baobaotao.domain.User; @Service //将userbean标注为一个服务层的Bean public class UserService { @Autowired private UserDao userDao; @Autowired private LoginLogDao loginLogDao; public boolean hasMatchUser(String userName, String passWord){ int matchCount = userDao.getMatchCount(userName, passWord); return matchCount>0; } public User findUserByUserName(String userName){ return userDao.findUserByUserName(userName); } public void loginSuccess(User user){ user.setCredits(5+user.getCredits()); LoginLog loginLog = new LoginLog(); loginLog.setUserId(user.getUserId()); loginLog.setIp(user.getLastIp()); loginLog.setLoginDate(user.getLastVisit()); userDao.updateLoginInfo(user); loginLogDao.insertLoginLog(loginLog); } } login.jsp [html] view plaincopyprint?在CODE上查看代码片派生到我的代码片 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>hehe</title> </head> <body> <c:if test="${!empty error}"> <c:out value="${error}" /> </c:if> <form action="<c:url value="loginCheck.html"/>" method="post"> 用户名: <input type="text" name="userName"> 密 码: <input type="password" name="password"> <input type="submit" value="登录" /> <input type="reset" value="重置" /> </form> </body> </html> 求教,异常如何处理呢? 求教,异常如何处理呢?
在中国程序员是青春饭吗?
今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...
《MySQL 性能优化》之理解 MySQL 体系结构
本文介绍 MySQL 的体系结构,包括物理结构、逻辑结构以及插件式存储引擎。
程序员请照顾好自己,周末病魔差点一套带走我。
程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。
复习一周,京东+百度一面,不小心都拿了Offer
京东和百度一面都问了啥,面试官百般刁难,可惜我全会。
Java 14 都快来了,为什么还有这么多人固守Java 8?
从Java 9开始,Java版本的发布就让人眼花缭乱了。每隔6个月,都会冒出一个新版本出来,Java 10 , Java 11, Java 12, Java 13, 到2020年3月份,...
达摩院十大科技趋势发布:2020 非同小可!
【CSDN编者按】1月2日,阿里巴巴发布《达摩院2020十大科技趋势》,十大科技趋势分别是:人工智能从感知智能向认知智能演进;计算存储一体化突破AI算力瓶颈;工业互联网的超融合;机器间大规模协作成为可能;模块化降低芯片设计门槛;规模化生产级区块链应用将走入大众;量子计算进入攻坚期;新材料推动半导体器件革新;保护数据隐私的AI技术将加速落地;云成为IT技术创新的中心 。 新的画卷,正在徐徐展开。...
轻松搭建基于 SpringBoot + Vue 的 Web 商城应用
首先介绍下在本文出现的几个比较重要的概念: 函数计算(Function Compute): 函数计算是一个事件驱动的服务,通过函数计算,用户无需管理服务器等运行情况,只需编写代码并上传。函数计算准备计算资源,并以弹性伸缩的方式运行用户代码,而用户只需根据实际代码运行所消耗的资源进行付费。Fun: Fun 是一个用于支持 Serverless 应用部署的工具,能帮助您便捷地管理函数计算、API ...
讲真,这两个IDE插件,可以让你写出质量杠杠的代码
周末躺在床上看《拯救大兵瑞恩》 周末在闲逛的时候,发现了两个优秀的 IDE 插件,据说可以提高代码的质量,我就安装了一下,试了试以后发现,确实很不错,就推荐给大家。 01、Alibaba Java 代码规范插件 《阿里巴巴 Java 开发手册》,相信大家都不会感到陌生,其 IDEA 插件的下载次数据说达到了 80 万次,我今天又贡献了一次。嘿嘿。 该项目的插件地址: https://github....
Python+OpenCV实时图像处理
目录 1、导入库文件 2、设计GUI 3、调用摄像头 4、实时图像处理 4.1、阈值二值化 4.2、边缘检测 4.3、轮廓检测 4.4、高斯滤波 4.5、色彩转换 4.6、调节对比度 5、退出系统 初学OpenCV图像处理的小伙伴肯定对什么高斯函数、滤波处理、阈值二值化等特性非常头疼,这里给各位分享一个小项目,可通过摄像头实时动态查看各类图像处理的特点,也可对各位调参、测试...
2020年一线城市程序员工资大调查
人才需求 一线城市共发布岗位38115个,招聘120827人。 其中 beijing 22805 guangzhou 25081 shanghai 39614 shenzhen 33327 工资分布 2020年中国一线城市程序员的平均工资为16285元,工资中位数为14583元,其中95%的人的工资位于5000到20000元之间。 和往年数据比较: yea...
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
害怕面试被问HashMap?这一篇就搞定了!
声明:本文以jdk1.8为主! 搞定HashMap 作为一个Java从业者,面试的时候肯定会被问到过HashMap,因为对于HashMap来说,可以说是Java集合中的精髓了,如果你觉得自己对它掌握的还不够好,我想今天这篇文章会非常适合你,至少,看了今天这篇文章,以后不怕面试被问HashMap了 其实在我学习HashMap的过程中,我个人觉得HashMap还是挺复杂的,如果真的想把它搞得明明白...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
python爬取百部电影数据,我分析出了一个残酷的真相
2019年就这么匆匆过去了,就在前几天国家电影局发布了2019年中国电影市场数据,数据显示去年总票房为642.66亿元,同比增长5.4%;国产电影总票房411.75亿元,同比增长8.65%,市场占比 64.07%;城市院线观影人次17.27亿,同比增长0.64%。 看上去似乎是一片大好对不对?不过作为一名严谨求实的数据分析师,我从官方数据中看出了一点端倪:国产票房增幅都已经高达8.65%了,为什...
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试,面试官没想到一个ArrayList,我都能跟他扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
2020 年,大火的 Python 和 JavaScript 是否会被取而代之?
Python 和 JavaScript 是目前最火的两大编程语言,但是2020 年,什么编程语言将会取而代之呢? 作者 |Richard Kenneth Eng 译者 |明明如月,责编 | 郭芮 出品 | CSDN(ID:CSDNnews) 以下为译文: Python 和 JavaScript 是目前最火的两大编程语言。然而,他们不可能永远屹立不倒。最终,必将像其他编程语言一...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
Idea 中最常用的10款插件(提高开发效率),一定要学会使用!
学习使用一些插件,可以提高开发效率。对于我们开发人员很有帮助。这篇博客介绍了开发中使用的插件。
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
作为一名大学生,如何在B站上快乐的学习?
B站是个宝,谁用谁知道???? 作为一名大学生,你必须掌握的一项能力就是自学能力,很多看起来很牛X的人,你可以了解下,人家私底下一定是花大量的时间自学的,你可能会说,我也想学习啊,可是嘞,该学习啥嘞,不怕告诉你,互联网时代,最不缺的就是学习资源,最宝贵的是啥? 你可能会说是时间,不,不是时间,而是你的注意力,懂了吧! 那么,你说学习资源多,我咋不知道,那今天我就告诉你一个你必须知道的学习的地方,人称...
那些年,我们信了课本里的那些鬼话
教材永远都是有错误的,从小学到大学,我们不断的学习了很多错误知识。 斑羚飞渡 在我们学习的很多小学课文里,有很多是错误文章,或者说是假课文。像《斑羚飞渡》: 随着镰刀头羊的那声吼叫,整个斑羚群迅速分成两拨,老年斑羚为一拨,年轻斑羚为一拨。 就在这时,我看见,从那拨老斑羚里走出一只公斑羚来。公斑羚朝那拨年轻斑羚示意性地咩了一声,一只半大的斑羚应声走了出来。一老一少走到伤心崖,后退了几步,突...
立即提问