1、spring框架介绍


spring框架介绍

为什么要出现spring?

业界追求软件高内聚、低耦合、性能好。可维护性好,可扩展性好。

如何做到高内聚?

让代码分层,每一层的分工明确,每一层都各司其职,利于代码的维护。

如何做到低耦合?

将每层的代码依赖降到最低,不会因为改变某层而影响到其他层,有利于我们的扩展。

如何做到性能好?

代码的优化。

什么是spring?

spring是一个轻量级的一站式的框架。支持插拔式的开发,只需要四个架包就可以启动起来。其他的架包只需要按需配置即可,还可以插入其他的框架。与早期的EJB的框架都属于javaEE企业级开发,EJB是重量级的。

spring的介绍

spring的启动

只需要四个jar包,还有一个是日志的依赖包。

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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 创建一个对象 -->
    <bean id="userService" class="cn.zj.spring.service.UserService"/>
</beans>

测试

@Test
	public void testBean() {
		//传统做法
//		UserService service = new UserService();
//		service.say();
		//读取配置文件
		ApplicationContext context=new  							   ClassPathXmlApplicationContext("applicationContext.xml");
		//创建bean对象
		UserService userService = context.getBean("userService",UserService.class);
		userService.say();
	}

IOC控制反转

IOC是控制反转,所谓控制反转就是将创建对象的事情交给spring容器,外界使用的时候只需要在spring容器中拿就行了。从而达到了对象不直接依赖在类中,达到了解耦。(不直接通过new的方式)

好莱坞法则,只有你跟我说你需要对象我就给你。

四种实例化bean的方式

  1. 构造器实例化

    <!-- 构造器实例化 (无参构造函数) -->
    	<!-- 默认情况下使用的方式,会自动调用无参构造函数 原理:反射 Class clz = Class.forName(""); clz.newInstance(); -->
    	<bean id="userService" class="cn.zj.spring.service.UserService"/>
    
  2. 静态工厂

    <!-- 静态工厂实例化 -->
    	<bean id="userService" class="cn.zj.spring.service.UserServiceFactory" 
    		factory-method="getObject" />
    
    /**
     * 静态工厂
     * @author lgx
     *
     */
    public class UserServiceFactory {
    	public static UserService getObject() {
    		System.out.println("静态工厂创建了UserService对象");
    		return new UserService();
    	}
    }
    
  3. 实例化工厂

    <!-- 实体工厂实例化 -->
    	<bean id="userService2Factory" class="cn.zj.spring.service.UserService2Factory"/> 
    		<bean id="userService" factory-bean="userService2Factory" factory-method="getObject"/>
    
    
    /**
     * 实体工厂
     * @author lgx
     *
     */
    public class UserService2Factory {
    	public UserService getObject() {
    		System.out.println("实体工厂创建了UserService对象");
    		return new UserService();
    	}
    
  4. 实现FactoryBean接口实例化:实例工厂变种

    <!-- 实现FactoryBean接口实例化:实例工厂变种 -->
    	<bean id="userService"
    		class="cn.zj.spring.service.UserService3Factory" />
    
    public class UserService3Factory implements FactoryBean<UserService>{
    	
    	//返回一个对象
    	@Override
    	public UserService getObject() throws Exception {
    		System.out.println("实现FactoryBean实例化");
    		return new UserService();
    	}
    	//返回对象的类型
    	@Override
    	public Class<?> getObjectType() {
    		return null;
    	}
    	//是否单例,true是,false不是
    	@Override
    	public boolean isSingleton() {
    		return false;
    	}
    

Ioc细节配置

可以配置别名,在bean中配置name,还有创建对象的scope。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd"
        default-init-method=""
        default-destroy-method=""
        >
	<!-- 细节配置 -->
	<!-- 配置别名 name:就是bean的id alias:就是获取bean对象时的名称 -->
	<alias name="userService" alias="us" />


	<!-- 创建一个对象 -->
	<!-- 配置name属性
	name: 可以配置多个name,中间用空格隔开
	id: 只能配置一个,如果中间有空格也会被当成一个整体
	 -->
	<!-- <bean name="uService service" id="userService" class="cn.zj.spring.service.UserService" /> -->
	
	<!-- 配置scope
	
	singleton:默认情况下创建的对象是单例的
	prototype: 多例的
	request:一次请求有效,在web项目
	session:一次会话有效,在web项目
	 -->
	<!-- <bean scope="prototype" id="userService" class="cn.zj.spring.service.UserService" />
 -->
 
    <!-- 
    init-method:在创建对象的时候就调用,每创建一次就调用,写方法名
    
    destroy-method:当spring容器销毁时,只有单例模式有效,,多例需手动调用,写方法名
     -->
	<bean  init-method="init" 
	destroy-method="destory"
	
	id="userService" class="cn.zj.spring.service.UserService" />

</beans>

DI依赖注入

当我们创建的对象交给了spring容器去做,那么对象与对象之间的关系怎么办呢?

此时我们就有了一个新的概念叫依赖注入,依赖注入就是处理对象与对象之间的关系。

依赖注入的四种方式

实体类:

User.java

package cn.zj.spring.pojo;

public class User {
	private Integer id;
	private String name;
	private Department dept;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Department getDept() {
		return dept;
	}
	public void setDept(Department dept) {
		this.dept = dept;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", dept=" + dept + "]";
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(Integer id, String name, Department dept) {
		super();
		this.id = id;
		this.name = name;
		this.dept = dept;
	}	
}

Department.java

package cn.zj.spring.pojo;

public class Department {
	private Integer id;
	private String name;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "Department [id=" + id + ", name=" + name + "]";
	}
	public Department() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Department(Integer id, String name) {
		super();
		this.id = id;
		this.name = name;
	}	
}

Collection.java

package cn.zj.spring.pojo;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class Collection {
	private String[] arr;
	private List list;
	private Set set;
	private Map map;
	private Properties props;
	public String[] getArr() {
		return arr;
	}
	public void setArr(String[] arr) {
		this.arr = arr;
	}
	public List getList() {
		return list;
	}
	public void setList(List list) {
		this.list = list;
	}
	public Set getSet() {
		return set;
	}
	public void setSet(Set set) {
		this.set = set;
	}
	public Map getMap() {
		return map;
	}
	public void setMap(Map map) {
		this.map = map;
	}
	public Properties getProps() {
		return props;
	}
	public void setProps(Properties props) {
		this.props = props;
	}
	public Collection() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Collection(String[] arr, List list, Set set, Map map, Properties props) {
		super();
		this.arr = arr;
		this.list = list;
		this.set = set;
		this.map = map;
		this.props = props;
	}
	@Override
	public String toString() {
		return "Collection [arr=" + Arrays.toString(arr) + ", list=" + list + ", set=" + set + ", map=" + map
				+ ", props=" + props + "]";
	}
}

方式:

  1. setting 注入

    <!--setting 注入 用得最多的 -->
    	<!-- 员工 -->
    	<bean id="user" class="cn.zj.spring.pojo.User"> 
    	<!-- name:属性的值 
    	     value:初始化的值,是值类型比如String,Integer等基本数据类型 
    		 ref:引用数据类型,引用spring中bean的id 
        -->
             <property name="id" value="12" /> 
             <property name="name" value="旺财" /> 
             <property name="dept" ref="dept" /> </bean>
    	<!-- 部门 -->
    	<bean id="dept" class="cn.zj.spring.pojo.Department"> 
    	   <property name="id"value="1" /> 
    	   <property name="name" value="人才部" /> 
    	</bean>
    
  2. 构造器注入

    <!-- 构造器注入 -->
    	<bean id="user" class="cn.zj.spring.pojo.User">
    	<!-- constructor-arg: argument参数的缩写 index:根据构造器的索引,不建议 name:根据属性的名字,推荐 type:属性的数据类 
    		value: 值类型,比如String,Integer等基本数据类型 ref: 引用数据类型 -->
    	<constructor-arg name="id" type="Integer" value="10"/> 
    	   <constructor-arg name="name" type="String" value="旺财s"/> 
    	   <constructor-arg ref="dept"/>关联另外的实体类 
    	</bean>
        <bean id="dept" class="cn.zj.spring.pojo.Department"> 
            <constructor-arg name="id" type="Integer" value="1"/> 
    		<constructor-arg name="name" type="String" value="销售部"/> 
        </bean>
    
  3. p命名空间注入

    1. 需要导入p命名空间约束

      xmlns:p="http://www.springframework.org/schema/p"
      
    2. <!-- p命名空间注入 -->
      	<!-- xmlns:p="http://www.springframework.org/schema/p" -->
      	<!-- p:属性= "值" p:属性-ref = bean.id -->
      	<bean id="user" class="cn.zj.spring.pojo.User" p:id = "2" p:name="蛋黄" 
      		p:dept-ref="dept"/> 
      	<bean id="dept" class="cn.zj.spring.pojo.Department" 
      		p:id="10" p:name="网络部"/>
      
  4. 集合注入

    <!-- 集合注入 -->
    	<bean id="collection" class="cn.zj.spring.pojo.Collection">
    		<!-- 数组注入 -->
    		<property name="arr">
    			<array>
    				<value>aa</value>
    				<value>bb</value>
    				<value>cc</value>
    			</array>
    		</property>
    		<!--list 集合注入 -->
    		<property name="list">
    			<list>
    				<value>111</value>
    				<value>111</value>
    				<value>222</value>
    			</list>
    		</property>
    		<!--set集合注入 -->
    		<property name="set">
    			<set>
    				<value>111</value>
    				<value>111</value>
    				<value>222</value>
    			</set>
    		</property>
    		<!-- map集合的注入 -->
    		<property name="map">
    			<map>
    				<entry key="key1" value="123" />
    				<entry key="key1" value="456" />
    				<entry key="key2" value="123" />
    			</map>
    		</property>
    		<!--Properties注入 -->
    		<property name="props">
    			<props>
    				<prop key="key1">aa</prop>
    				<prop key="key1">vv</prop>
    				<prop key="key2">cc</prop>
    			</props>
    		</property>
    	</bean>
    

Properteis文件的配置

spring管理数据库的操作,比如事务的处理,Connection对象的管理。现在配置druid-1.1.9.jar的连接池。

druid-1.1.9.jar:是阿里巴巴开发的,目前最快,最流行的连接池。

db.properties配置文件

useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT mysql8.0以上需要配置此

#数据库连接四要素
jdbc.driverClassName = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
jdbc.username = root
jdbc.password = root
#最大连接数
jdbc.maxActive = 10

applicationContext.xml配置

需要先导入context约束

xmlns:context="http://www.springframework.org/schema/context"

需要添加到xsi:schemaLocation中

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM