码迷,mamicode.com
首页 > 编程语言 > 详细

Java学习之:Spring的扩展配置

时间:2019-10-14 14:42:41      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:www   信息   argument   The   color   mode   cep   数据   ngx   

  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的扩展配置

标签:www   信息   argument   The   color   mode   cep   数据   ngx   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!