1.spring是一个类管理框架
2.使用spring管理起来的类,scope为singleton的时候,在加载spring配置文件时候,会加载放进servlet容器中,相当于java的堆,这个时候从容器中getBena出来的对象,始终是同一个,假如在配置文件中对象的属性就已初始化,则使用其对象get出来的属性值就为初始化的值。这样的好处是节省资源,个人理解用处最好用在项目中的定时任务接口方面。
名为bean.xml的spring配置文件:首先配置一个无参构造器的类对象,当使用无参构造器初始化类时,属性userName时
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--这是无参构造器类配置写法-->
<bean id="user" class="com.vo.user" scope="singleton">
<property name="userName" value="莉莉" ></property>
</bean>
<!--这是有参构造器类配置写法-->
<bean id="user_123" class="com.vo.user" scope="singleton">
<<constructor-arg index="0" type="java.lang.String" value="莉莉" ></constructor-arg>
</bean>
<beans>
获取对象代码:使用ClassPathXmlApplicationContext对象获取servlet容器中的对象(粗略看过源码,对象是由代理对象,并不是目标对象本身,代理对象与目标对象具体差异请参考https://www.cnblogs.com/qlqwjy/p/7550609.html。)
ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
User user=context.get("user");
System.out.println(user.getUserName());
user.setUserName("丁丁")
user.setId(123);
User user_1=context.get("user");
System.out.println(user_1.getUserName()+user_1.getId());
控制台先后输出结果为 “莉莉”
“丁丁123”;
3.spring可以管理数据源,使用数据连接池,这样能节省许多与数据库交互的cpu资源,其实个人理解应该就是多线程了
使用阿里云druid连接池(这里只记录最好用的,c3p0链接池太浅,不适合项目级别的开发),这个druid连接池可存放十几万条数据库连接通道,使用Jar包网上下载即可——druid-1.0.29.jar
spring配置文件中配置写法,这里我们用properties文件存放数据库连接信息,然后去读取放进配置文件的方式。
<?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"
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">
<!-- 配置多个properties文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!-- 配置的是druid数据源 ,使用SPEL表达式获取properties文件的参数-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbcUrl}"></property>
<property name="username" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="initialSize" value="2000"></property>
<property name="minIdle" value="1500"></property>
<property name="maxActive" value="5000"></property>
</bean>
</beans>
java中导入druid对象为DruidDataSource,此类本身就重写了toString,直接输出在控制台就可以查看链接池状况