Java学习之:Spring的扩展配置

  1、在配置文件applicationContext.xml中,引入相关的配置文件方式:

  2、使用Jndi数据源的方式改造配置文件applicationContext.xml:

  3、注释配置文件applicationContext.xml中的数据源:

  4、找到安装Tomcat的文件夹,在conf目录下打开context.xml配置文件,添加如下代码:

  5、在包com.javaxyz.servlet下,创建UserServlet.java文件

  6、控制台显示结果:

  7、bug场景:引入database.properties配置文件时报错:

  1、在配置文件applicationContext.xml中,引入相关的配置文件方式:

  classpath:database.properties

  2、使用Jndi数据源的方式改造配置文件applicationContext.xml:

  java:comp/env/jdbc/java

  3、注释配置文件applicationContext.xml中的数据源:

  4、找到安装Tomcat的文件夹,在conf目录下打开context.xml配置文件,添加如下代码:

  type="javax.sql.DataSource"

  auth="Container"

  driverClassName="com.mysql.jdbc.Driver"

  url="jdbc:mysql:///p19_java7_mybatis"

  username="root"

  password="aaa"

  maxActive="100"

  maxIdle="50"

  maxWait="1000"

  />

  5、在包com.javaxyz.servlet下,创建UserServlet.java文件

  /**

  * @Author:DongGaoYun

  * @Description:

  * @Date 2019-10-9 下午5:11:10

  * @Version 1.0

  * @Company: www.springhome.org

  */

  package com.javaxyz.servlet;

  import java.io.IOException;

  import java.io.PrintWriter;

  import java.text.ParseException;

  import java.text.SimpleDateFormat;

  import java.util.ArrayList;

  import java.util.Date;

  import java.util.List;

  import javax.servlet.ServletException;

  import javax.servlet.http.HttpServlet;

  import javax.servlet.http.HttpServletRequest;

  import javax.servlet.http.HttpServletResponse;

  import org.apache.log4j.Logger;

  import org.junit.Test;

  import org.springframework.context.ApplicationContext;

  import org.springframework.context.support.ClassPathXmlApplicationContext;

  import com.javaxyz.entity.User;

  import com.javaxyz.service.UserService;

  import com.javaxyz.test.SpringTest;

  /**

  * @ClassName:UserServlet.java

  * @Description:描述信息

  * @Author:DongGaoYun

  * @Author English name:Andy

  * @URL:www.javaxyz.com 或 www.gyun.org

  * @Email:[email protected]

  * @QQ:1050968899

  * @WeiXin:QingYunJiao

  * @WeiXinGongZhongHao: JavaForum

  * @Date:2019-10-9 下午5:11:10

  * @Version:1.0

  */

  public class UserServlet extends HttpServlet {

  private static Logger logger = Logger.getLogger(UserServlet.class);

  /**

  * The doGet method of the servlet.

  *

  * This method is called when a form has its tag value method equals to get.

  *

  * @param request

  * the request send by the client to the server

  * @param response

  * the response send by the server to the client

  * @throws ServletException

  * if an error occurred

  * @throws IOException

  * if an error occurred

  */

  public void doGet(HttpServletRequest request, HttpServletResponse response)

  throws ServletException, IOException {

  doPost(request, response);

  }

  /**

  * The doPost method of the servlet.

  *

  * This method is called when a form has its tag value method equals to

  * post.

  *

  * @param request

  * the request send by the client to the server

  * @param response

  * the response send by the server to the client

  * @throws ServletException

  * if an error occurred

  * @throws IOException

  * if an error occurred

  */

  public void doPost(HttpServletRequest request, HttpServletResponse response)

  throws ServletException, IOException {

  /*

  * add用户信息 UserService调用 配置声明式事务

  */

  ApplicationContext context = new ClassPathXmlApplicationContext(

  "applicationContext.xml");

  // 原来是通过映射接口去调用

  // UserMapper userMapper = (UserMapper) context.getBean("userMapper");

  //

  String[] bean = context.getBeanDefinitionNames();

  for (String string : bean) {

  System.out.println(string);

  }

  // 现在是通过业务接口去调用

  UserService service = (UserService) context.getBean("userService");

  User user = new User();

  user.setUserCode("zhangxiulian");

  user.setUserName("张秀连666");

  /**

  * userCode, userName, userPassword, gender, birthday, phone, address,

  * userRole, createdBy, creationDate

  */

  user.setUserPassword("123999");

  user.setGender(0);

  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

  try {

  user.setBirthday(sdf.parse("2010-9-17"));

  } catch (ParseException e) {

  e.printStackTrace();

  }

  user.setPhone("13608880888");

  user.setAddress("养育巷49");

  user.setUserRole(2);

  user.setCreatedBy(1);

  user.setCreationDate(new Date());

  Integer userRole = 2;

  // int num = userMapper.addUser(user);

  List listUsers = new ArrayList();

  listUsers.add(user);

  listUsers.add(user);

  int num = service.saveUser(listUsers);

  if (num > 0) {

  logger.info("增加成功!");

  } else {

  logger.error("增加失败!");

  }

  }

  }

  注意:使用jndi数据源,显示结果需要启动Tomcat服务器,执行web路径: http://localhost:9999/java7_chapter7_spring2_jndi/userServlet

  6、控制台显示结果:

  - (1061 ms) - 2019-10-9 17:15:13[DEBUG](PropertySourcesPropertyResolver.java:103) Could not find key ‘spring.liveBeansView.mbeanDomain‘ in any property source. Returning [null]

  org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0

  dataSource

  sqlSessionFactory

  org.mybatis.spring.mapper.MapperScannerConfigurer#0

  userService

  org.springframework.context.annotation.internalConfigurationAnnotationProcessor

  org.springframework.context.annotation.internalAutowiredAnnotationProcessor

  org.springframework.context.annotation.internalRequiredAnnotationProcessor

  org.springframework.context.annotation.internalCommonAnnotationProcessor

  transactionManager

  org.springframework.aop.config.internalAutoProxyCreator

  org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0

  org.springframework.transaction.interceptor.TransactionInterceptor#0

  org.springframework.transaction.config.internalTransactionAdvisor

  org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor

  userMapper

  - (1061 ms) - 2019-10-9 17:15:13[DEBUG](AbstractBeanFactory.java:243) Returning cached instance of singleton bean ‘userService‘

  - (1063 ms) - 2019-10-9 17:15:13[DEBUG](AbstractBeanFactory.java:243) Returning cached instance of singleton bean ‘org.springframework.transaction.interceptor.TransactionInterceptor#0‘

  - (1066 ms) - 2019-10-9 17:15:13[DEBUG](AbstractFallbackTransactionAttributeSource.java:107) Adding transactional method ‘UserServiceImpl.saveUser‘ with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ‘‘

  - (1069 ms) - 2019-10-9 17:15:13[DEBUG](AbstractBeanFactory.java:243) Returning cached instance of singleton bean ‘transactionManager‘

  - (1076 ms) - 2019-10-9 17:15:13[DEBUG](AbstractPlatformTransactionManager.java:366) Creating new transaction with name [com.javaxyz.service.impl.UserServiceImpl.saveUser]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ‘‘

  - (1078 ms) - 2019-10-9 17:15:13[DEBUG](DataSourceTransactionManager.java:204) Acquired Connection [jdbc:mysql:///p19_java7_mybatis, [email protected], MySQL-AB JDBC Driver] for JDBC transaction

  - (1087 ms) - 2019-10-9 17:15:13[DEBUG](DataSourceTransactionManager.java:221) Switching JDBC Connection [jdbc:mysql:///p19_java7_mybatis, [email protected], MySQL-AB JDBC Driver] to manual commit

  - (1093 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) Creating a new SqlSession

  - (1099 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) Registering transaction synchronization for SqlSession [[email protected]]

  - (1138 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) JDBC Connection [jdbc:mysql:///p19_java7_mybatis, [email protected], MySQL-AB JDBC Driver] will be managed by Spring

  - (1141 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) ooo Using Connection [jdbc:mysql:///p19_java7_mybatis, [email protected], MySQL-AB JDBC Driver]

  - (1146 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) ==> Preparing: INSERT INTO smbms_user (userCode, userName, userPassword, gender, birthday, phone, address, userRole, createdBy, creationDate) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);

  - (1172 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) ==> Parameters: zhangxiulian(String), 张秀连666(String), 123999(String), 0(Integer), 2010-09-17 00:00:00.0(Timestamp), 13608880888(String), 养育巷49(String), 2(Integer), 1(Integer), 2019-10-09 17:15:13.769(Timestamp)

  - (1175 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) Releasing transactional SqlSession [[email protected]]

  - (1176 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) Fetched SqlSession [[email protected]] from current transaction

  - (1177 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) ooo Using Connection [jdbc:mysql:///p19_java7_mybatis, [email protected], MySQL-AB JDBC Driver]

  - (1178 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) ==> Preparing: INSERT INTO smbms_user (userCode, userName, userPassword, gender, birthday, phone, address, userRole, createdBy, creationDate) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);

  - (1178 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) ==> Parameters: zhangxiulian(String), 张秀连666(String), 123999(String), 0(Integer), 2010-09-17 00:00:00.0(Timestamp), 13608880888(String), 养育巷49(String), 2(Integer), 1(Integer), 2019-10-09 17:15:13.769(Timestamp)

  - (1180 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) Releasing transactional SqlSession [[email protected]]

  - (1180 ms) - 2019-10-9 17:15:13[DEBUG](AbstractPlatformTransactionManager.java:753) Initiating transaction commit

  - (1181 ms) - 2019-10-9 17:15:13[DEBUG](DataSourceTransactionManager.java:267) Committing JDBC transaction on Connection [jdbc:mysql:///p19_java7_mybatis, [email protected], MySQL-AB JDBC Driver]

  - (1188 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) Transaction synchronization committing SqlSession [[email protected]]

  - (1188 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) Transaction synchronization closing SqlSession [[email protected]]

  - (1191 ms) - 2019-10-9 17:15:13[DEBUG](DataSourceTransactionManager.java:325) Releasing JDBC Connection [jdbc:mysql:///p19_java7_mybatis, [email protected], MySQL-AB JDBC Driver] after transaction

  - (1191 ms) - 2019-10-9 17:15:13[DEBUG](DataSourceUtils.java:327) Returning JDBC Connection to DataSource

  - (1192 ms) - 2019-10-9 17:15:13[ INFO](UserServlet.java:126) 增加成功!

  7、bug场景:引入database.properties配置文件时报错:

  重点:

  Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder ‘users‘ in string value "${users}"

  报错详情:无锡男科医院哪家好 http://www.bhnkyixue.com/

  - (369 ms) - 2019-10-9 16:34:56[ WARN](AbstractApplicationContext.java:486) Exception encountered during context initialization - cancelling refresh attempt

  org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name ‘dataSource‘ defined in class path resource [applicationContext.xml]: Could not resolve placeholder ‘users‘ in string value "${users}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder ‘users‘ in string value "${users}"

  at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:209)

  at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.processProperties(PropertyPlaceholderConfigurer.java:223)

  at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:84)

  at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:696)

  at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:671)

  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461)

  at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)

  at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)

  at com.javaxyz.test.SpringTest.test9(SpringTest.java:48)

  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)

  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

  at java.lang.reflect.Method.invoke(Method.java:606)

  at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)

  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)

  at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)

  at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)

  at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)

  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)

  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)

  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)

  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)

  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)

  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)

  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)

  at org.junit.runners.ParentRunner.run(ParentRunner.java:236)

  at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)

  at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)

  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)

  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)

  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)

  at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

  Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder ‘users‘ in string value "${users}"

  at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:173)

  at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:125)

  at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer$PlaceholderResolvingStringValueResolver.resolveStringValue(PropertyPlaceholderConfigurer.java:258)

  at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveStringValue(BeanDefinitionVisitor.java:282)

  at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveValue(BeanDefinitionVisitor.java:204)

  at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitPropertyValues(BeanDefinitionVisitor.java:141)

  at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitBeanDefinition(BeanDefinitionVisitor.java:82)

  at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:206)

  ... 31 more

  - (371 ms) - 2019-10-9 16:34:56[ INFO](DefaultSingletonBeanRegistry.java:444) Destroying singletons in org.s[email protected]6a109ac: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,sqlSessionFactory,org.mybatis.spring.mapper.MapperScannerConfigurer#0,userService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,userMapper]; root of factory hierarchy

  报错位置:

  报错原因是配置文件database.properties里用户名的key是user,而不是users

  user=root

原文地址:https://www.cnblogs.com/djw12333/p/11671175.html

时间: 2024-10-18 14:27:19

Java学习之:Spring的扩展配置的相关文章

win7+64位+Java学习基本软件安装+环境配置+eclipse(IDE)

一.下载安装JDK 1.安装包下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk9-downloads-3848520.html 根据需要进行下载,我的电脑是win7+64位,所以选择版本:jdk-9.0.1_windows-x64_bin.exe 2.双击安装包 ,点击下一步,建议不要装在C盘,我一般习惯性将所有软件装在E盘下面,首先是安装JDK: 3.继续点击下一步,安装完jdk-9.0.1,会自动安装jre-9.

Core Java 学习笔记——1.术语 环境配置/Eclipse汉化字体快捷键/API文档

今天起开始学习Java,学习用书为Core Java.之前有过C的经验.准备把自己学习这一本书时的各种想法,不易理解的,重要的都记录下来.希望以后回顾起来能温故知新吧.也希望自己能够坚持把自己学习这本书的整个过程记录下来. I want to put a ding in the universe. 基本术语:       Object Oriented Programming——OOP——面向对象编程 Application Programming Interface——API——应用程序编程接

JAVA学习之路(环境配置,)

最近过去的寒假我就开始看一些JAVA的学习视频了,视频是毕向东老师的,讲得还不错,东北口音,欧了没? 首先是一些基础概念. 1.JAVA的三种技术架构 企业版 J2EE 标准版 J2SE 小型版 J2ME 2.JAVA语言的特点:跨平台性 简言之,不同的平台都有与之对应的JVM.即Windows系统有win版的JVM,linux系统有linux版的JVM,Mac系统有Mac版的JVM,而JAVA程序是在这些虚拟机上开发的. 3.JAVA语言的环境搭建 自从sun公司被oracle收购以后,下载J

Java学习笔记:Spring框架

1.什么是Spring? 1.1 spring 是一个开源框架 1.2 spirng 为简化企业级应用开发而生,使用 spring 可以使简单的 JavaBean 实现以前只有 EJB 才能实现的功能 1.3 spring 是一个 IOC(DI) 和 AOP 容器框架 2.Spring入门示例   2.1 HelloWorld.java package com.oneline.spring.day01; public class HelloWorld { private String name;

基于Spring Cloud的微服务构建学习-3 Spring Cloud Eureka配置详解

配置详解 在Eureka的服务治理体系中,主要分为服务端与客户端.服务端为服务注册中心,而客户端为各个提供接口的微服务应用.当部署高可用注册中心时,每个服务端也已经成为了客户端,因此,在使用Spring Cloud Eureka的过程中,我们所做的配置内容几乎都是对Eureka客户端配置进行的操作,所以了解这部分的配置内容,对于用好Eureka非常有帮助. 而Eureka服务端更多类似于一个现成产品,大多数情况下,我们不需要修改它的配置信息. Eureka客户端配置分类 服务注册相关配置,包括服

java 学习第4课,配置android

昨天与今天都在配置安卓的开发环境, 搞的头都大了,步骤比较多 1. 先下载安装 java 的 jdk ,这个是最基础的组件 2. 再下载 android SDK,  http://developer.android.com/sdk/index.html  这个地址我本地打不开,结果我只能在自己的VPS服务器中先下载好,再下传到本地 下载后,解压出来,直接打开 Android SDK Manager 进行配置,下载所需的 这里至少要选中最新的Android 4.0 SDK 平台 和 Extras

【java学习】spring mvc 公共dao的实现,定义基本的增删改查

接口类: package com.blog.db.dao; import com.blog.util.Pagination; import java.util.List; public interface PublicDao<T> { public void setMapper(Class t); public void setTableName(String tn); public List<T> queryList(Pagination pagination); public

Java学习笔记——Linux下安装配置MySQL

山重水复疑无路,柳暗花明又一村 --游山西村 系统:Ubuntu 16.04LTS 1\官网下载mysql-5.7.18-linux-glibc2.5-x86_64.tar.gz 2\建立工作组:$su#groupadd mysql#useradd -r -g mysql mysql 3\创建目录#mkdir /usr/local/mysql#mkdir /usr/local/mysql/data 4\解压mysql-5.7.18-linux-glibc2.5-x86_64.tar.gz,并拷贝

基于纯Java代码的Spring容器和Web容器零配置的思考和实现(3) - 使用配置

经过<基于纯Java代码的Spring容器和Web容器零配置的思考和实现(1) - 数据源与事务管理>和<基于纯Java代码的Spring容器和Web容器零配置的思考和实现(2) - 静态资源.视图和消息器>两篇博文的介绍,我们已经配置好了Spring所需的基本配置.在这边博文中,我们将介绍怎么使用这些配置到实际项目中,并将web.xml文件替换为一个Java类. 我们使用Java代码来配置Spring,目的就是使我们的这些配置能够复用,对于这些配置的复用,我们采用继承和引入来实现