小言_互联网的博客

Spring-DI与IOC

531人阅读  评论(0)

Spring基础

框架介绍

定义

一系列jar包的组合

作用

1.提高开发效率
2.提供了代码规范,方便维护
3.提高代码重用性
4.针对一种特殊问题的解决访问

Spring框架

定义

Spring是一个轻量级控制反转(IOC)和面向切面编程(AOP)的容器框架
(1)轻量级:
开发使用比较简单,功能强大;
(2)IOC(Inverse of control):
将创建对象的权利交给Spring容器(不再使用以前new关键字创建对象);
(3)AOP(Aspect Oriented Programming):
将相同的逻辑抽取出来,即将业务逻辑从应用服务中分离出来。然后以拦截的方式作用在一个方法的不同位置。例如日志,事务的处理
(4)容器框架:

第一个spring

步骤

1.导入jar包(5个)
2.在resources或src文件下创建一个ApplicationContext.xml文件
3.创建一个测试类
4.在xml文件中添加id(类名,但首字母小写),class中添加(完全限定名)

代码实例

这是配置文件
<?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="person" class="cn.itsource.bean.Person" >
	</bean>
</beans>
person类
public class Person {
	public void work(){
		System.out.println("我爱java");
	}
}
测试类
//最常用 使用ApplicationContext来获得 配置文件的实例化
	@Test
	public void test2(){
		//创建容器对象,将配置文件交给容器管家
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
		//通过实例化对象来使用getBean(id,字节码对象)来获得Bean对象
		Person person = context.getBean("person",Person.class);
		person.work();
	}

spring细节

1.XML中的ID属性推荐与该类的首字母小写
2.作用域
单例:默认为单利,scope=“singleton”
多例:scope=“prototype”
3.懒加载/延迟加载
在获取或使用的时候才进行加载
单例:默认为迫切加载(加载完配置文件就加载),可设置为懒加载。全局:default-lazy-init=“true” 局部懒加载:lazy-init=“true” 全局更大,可以覆盖局部
多例:默认为懒加载

spring生命周期

Bean对象的生命周期指的是:从对象创建、初始化、调用执行到销毁的一个过程
实例化(无参公有构造)、初始化(通过init-method指定方法、服务(程序中使用)、销毁(通过destroy-method指定方法))

person代码
package cn.itsource.bean;

public class Person {
	public void work(){
		System.out.println("我爱java");
	}
	public Person() {
		System.out.println("我要开始学习了");
	} 
	public void init() {
		System.out.println("初始化");
	}
	public void destroy() {
		System.out.println("销毁");
	}
}
<?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-lazy-init="true">
	<bean id="person" class="cn.itsource.bean.Person">
	</bean>
	<bean id="localDateTime" class="java.time.LocalDateTime" init-method="init" destroy-method="destroy">
	</bean>

ApplicationContext与BeanFactory的区别

联系
1.ApplicationContext是BeanFactory的子类,都是bean工厂,拥有更多的功能与方法;
区别
1.ApplicationContext默认是在读取配置文件的时候就会根据配置创建Bean对象(迫切加载)。
2.BeanFactory是在使用的时候才进行对象的创建(懒加载/延迟加载)
扩展
1.我们在使用ApplicationContext的时候,可以通过配置让它也变成与BeanFactory一样的懒加载:

Spring测试

1.导包

spring-test-4.1.2.RELEASE.jar  测试包
spring-aop-4.1.2.RELEASE.jar  AOP包

2.在类中使用注解帮助我们进行测试
@RunWith:表示先启动Spring容器,把junit运行在Spring容器中;
@ContextConfiguration(“classpath:applicationContext.xml”):表示从CLASSPATH路径去加载资源文件;
@Autowired:表示自动装配,自动从Spring容器中取出对应bean赋值给当前使用的属性;

//加载Sping测试
@RunWith(SpringJUnit4ClassRunner.class)
//加载读取相应的配置文件,如果括号内容为空则将默认寻找该类下的 -Context.xml文件
@ContextConfiguration("classpath:ApplicationContext.xml")
public class SpringTest {
	//自动注入,程序自动匹配xml中的bean内容。如果匹配成功则赋值给该变量
	//先进行id匹配,然后再进行类型匹配
	@Autowired
	private Person person;
	@Test
	public void test(){
		person.work();
        
	}
}

Spirng注入

1.Spring注入对象大致分为两种:构造器注入Setter方法注入(Bean属性注入);
2.依赖性比较强的使用构造器注入,其他的使用setter方法注入;
3.一般使用属性注入(setter)

xml文件
<bean id="phone" class="cn.itsource.bean.Phone">
		<!-- 构造器注入 -->
		<constructor-arg index="0" value="麒麟980"></constructor-arg>
		<!-- 依赖注入 -->
		<property name="sim" value="19xxxxxxxx19"></property>
		<property name="sd" value="32G"></property>
	</bean>
person文件
package cn.itsource.bean;

public class Phone {
	public String cpu;
	public String sim;
	public String sd;
	@Override
	public String toString() {
		return "Phone [cpu=" + cpu + ", sim=" + sim + ", sd=" + sd + "]";
	}
	public void setSim(String sim) {
		this.sim = sim;
	}
	public void setSd(String sd) {
		this.sd = sd;
	}
	public Phone(String cpu) {
		this.cpu = cpu;
	}
	public Phone() {
	}
}

测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:ApplicationContext.xml")
public class SpringPhoneTest {
	@Autowired
	private Phone phone;
	@Test
	public void test(){
		System.out.println(phone);
	}
}
运行结果
Phone [cpu=麒麟980, sim=19xxxxxxxx19, sd=32G]

三层架构中Spring的使用

知识回顾

1.表现层(Web,GUI,…):现在咱们做的jsp/servlet(struts2)就是开发表现层
2.业务层(service):处理相应的业务,由表现层调用,方便维护和修改
3.持久层(dao):做数据的持久化(专门操作数据库的代码)。可以使用JDBC、SpringJDBC、Hibernate、MyBatis;

使用步骤

1.创建数据库 创建表user – id + name
2.创建创建包cn.itsource.project.domain – 实体类User
3.导入连接池2个+1个驱动包
4.将BasicDataSource交给Spring管理 – 注入4个 (driverClassName,url,username,password)bean属性
5.再注入时:传值使用db.properties来解决硬编码问题
7.测试BasicDataSource对象的创建 和 连接的获取
8.编写实现类

xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	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

http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
	<context:property-placeholder location="classpath:db.properties" system-properties-mode="NEVER"/>
	<bean id="db" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${driverClassName}"></property>
		<property name="username" value="${username}"></property>
		<property name="url" value="${url}"></property>
		<property name="password" value="${password}"></property>
	</bean>
</beans>
测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class StudentTest {
	@Autowired
	private BasicDataSource source;
	@Test
	public void tests(){
	Student user = new Student("帅");
	1.获取连接(连接池获取连接)
	Connection conn = db.getConnection();
	//2.准备sql语句
	String sql = "insert into user(name) values (?)";
	//3.获取语句对象
	PreparedStatement ps = conn.prepareStatement(sql);
	ps.setString(1, user.getName());
	//4.执行sql语句
	ps.executeUpdate();
	//5.释放资源
	ps.close();
	conn.close();

重点总结

1.知道Spring定义中的四个特征:轻量级 IOC AOP 框架容器
2.知道Spring再xml配置文件中的默认内容是:默认为单利—迫切加载。如果要切换为多利(scope=“prototype”),切换为懒加载(lazy-init=“true”)
3.Spring中使用注解来加载Sping框架,加载配置文件,Spring自动装配
@RunWith:表示先启动Spring容器,把junit运行在Spring容器中;
@ContextConfiguration(“classpath:applicationContext.xml”):表示从CLASSPATH路径去加载资源文件;
@Autowired:表示自动装配,自动从Spring容器中取出对应bean赋值给当前使用的属性;
4.Spring的属性注入:要具有相应setter方法


转载:https://blog.csdn.net/ChengHuanHuaning/article/details/102489605
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场