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:DongGaoYun@qq.com

  * @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, UserName=root@localhost, 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, UserName=root@localhost, 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 [org.apache.ibatis.session.defaults.DefaultSqlSession@1cd1130a]

  - (1138 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) JDBC Connection [jdbc:mysql:///p19_java7_mybatis, UserName=root@localhost, 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, UserName=root@localhost, 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 [org.apache.ibatis.session.defaults.DefaultSqlSession@1cd1130a]

  - (1176 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1cd1130a] from current transaction

  - (1177 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) ooo Using Connection [jdbc:mysql:///p19_java7_mybatis, UserName=root@localhost, 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 [org.apache.ibatis.session.defaults.DefaultSqlSession@1cd1130a]

  - (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, UserName=root@localhost, MySQL-AB JDBC Driver]

  - (1188 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) Transaction synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1cd1130a]

  - (1188 ms) - 2019-10-9 17:15:13[DEBUG](JakartaCommonsLoggingImpl.java:46) Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1cd1130a]

  - (1191 ms) - 2019-10-9 17:15:13[DEBUG](DataSourceTransactionManager.java:325) Releasing JDBC Connection [jdbc:mysql:///p19_java7_mybatis, UserName=root@localhost, 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.springframework.beans.factory.support.DefaultListableBeanFactory@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

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

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

    一.下载安装JDK 1.安装包下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk9-downloads-3848520.h ...

  2. 【Java Web开发学习】Spring MVC 开始配置

    Spring MVC 开始配置 转载:http://www.cnblogs.com/yangchongxing/p/8871370.htm 学习搭建最简单的Spring MVC框架. ======== ...

  3. Spring boot 官网学习笔记 - Spring Boot 属性配置和使用(转)-application.properties

    Spring Boot uses a very particular PropertySource order that is designed to allow sensible overridin ...

  4. java 实现类似spring的可配置的AOP框架

    一.工厂类BeanFactory: 1.工厂类BeanFactory负责创建目标类或代理类的实例对象,并通过配置文件实现切换. 2.getBean方法根据参数字符串返回一个相应的实例对象,如果参数字符 ...

  5. java学习第一天:环境的配置

    1.下载JDK,当前版本下载地址为:http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.htm ...

  6. java学习之spring基础

    0x00前言 spring框架应用的是ioc模式,ioc模式是指控制反转模式,本质是你不去创建对象让spring框架给你创建对象你去使用对象.多种开发模式通过配置文件和注解的方式去开发的都很值得去学习 ...

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

    最近过去的寒假我就开始看一些JAVA的学习视频了,视频是毕向东老师的,讲得还不错,东北口音,欧了没? 首先是一些基础概念. 1.JAVA的三种技术架构 企业版 J2EE 标准版 J2SE 小型版 J2 ...

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

    今天起开始学习Java,学习用书为Core Java.之前有过C的经验.准备把自己学习这一本书时的各种想法,不易理解的,重要的都记录下来.希望以后回顾起来能温故知新吧.也希望自己能够坚持把自己学习这本 ...

  9. java框架之Spring(2)-注解配置IOC&AOP配置

    注解配置IoC 准备 1.要使用注解方式配置 IoC,除了之前引入的基础 jar 包,还需要引入 spring-aop 支持包,如下: 2.在 applicationContext.xml 中引入 c ...

随机推荐

  1. python nose 自写插件打乱class类中用例执行顺序,但将test_a和test_z排除

    在使用nose时,有这样一个需求,用例执行打乱,但部分用例因场景原因必须先执行,这类用例在写用例时人为的加上了test_a或test_z字样 网上找了一圈,都没找到合适的方法,只有自己写插件了 已写完 ...

  2. 洛谷P1230智力大冲浪 题解

    题目描述 小伟报名参加中央电视台的智力大冲浪节目.本次挑战赛吸引了众多参赛者,主持人为了表彰大家的勇气,先奖励每个参赛者m元.先不要太高兴!因为这些钱还不一定都是你的?!接下来主持人宣布了比赛规则: ...

  3. 解决github clone慢的问题

    github clone非常慢,解决方法,首先要有vpn 参考 https://www.zhihu.com/question/27159393 第一种方法 这种是没有vpn的方法,测试从10k到 几十 ...

  4. 【技术博客】移动端的点击事件与Sticky Hover问题

    目录 移动端的点击事件与Sticky Hover问题 TL;DR 前言 问题描述 背景 实现方式 问题 关于移动端浏览器的点击事件 初次发现问题后各种解决尝试:从点击事件本身下手 cursor: po ...

  5. kali 添加swap 交换分区

    这里采用的是添加交换文件 mkdir /swap #创建/swap 文件夹 dd if=/dev/zero of=/swap/swapfile bs=1M count=4096 # 在/swap 下创 ...

  6. linux lnmp安装2个版本PHP教程

    linux lnmp安装2个版本PHP教程我原先装了5.6版本的PHP 后来想装个PHP7.0.14版本 一方面看看稳定性 另一方面看看性能怎么样 其实原理很简单 php-fpm开启了1个端口来管理P ...

  7. 【C++】一个指针占几个字节?为什么呢?

    一个指针在32位操作系统上,占4个字节 一个指针在64位操作系统上,占8个字节 但是,编译器为了兼容32位操作系统和64位操作系统,所以指针都是4个字节长度 为什么呢? 在计算机中,CPU不能直接与硬 ...

  8. 027 ElasticSearch----全文检索技术02---快速入门

    1.基本概念 Elasticsearch也是基于Lucene的全文检索库,本质也是存储数据,很多概念与MySQL类似的. 注意:6.0之前的版本有type(类型)概念,type相当于关系数据库的表,E ...

  9. Aliyun发送短信接口调用方法

    aliyun新版发送短信讲的不是很清晰,初次使用一堆dll不知道用哪个,以.net为例 申请SignName与Template_code请先申请,一般两个小时能通过 一.https://help.al ...

  10. 单词uranolite陨石uranolite英语

    陨石(uranolite)是指来自地球以外太阳系其他天体的碎片,绝大多数来自位于火星和木星之间的小行星,少数来自月球(40块)和火星(40块).全世界已收集到4万多块陨石样品,石陨石主要成分是硅酸盐. ...