spring Ioc详细配置

配置环境

在这里插入图片描述

案例一

用xml配置类对象创建bean

(1)、	<bean id="" class=""></bean>

id: 给类定义一个唯一的标识(名称)
class : 需要被beanFactory new出来的类的路径

(2)、源代码

User.java

package com.pojo;

public class User {
	
	public void add() {
		System.out.println("add..........");
	}

}

配置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">

	<!-- 配置User对象创建 -->
	<bean id="user" class="com.pojo.User"></bean>

</beans>

测试类:

package com.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.pojo.User;

public class IocTest {
	
	// 测试User对象创建
	@Test
	public void testAdd() {
		// 1加载spring的配置文件
		ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
		
		// 获取配置创建的对象
		User user = context.getBean("user",User.class);
		user.add();	
	}


}

结果
在这里插入图片描述

Ioc容器

本质上就是一个beanFactory,Ioc就是beanFactory帮助用户new bean
从本质上来说,Ioc就是DI
Ioc–控制反转:交出new bean的控制权给spring框架
DI—依赖注入:给bean的成员变量赋值

Ioc操作bean

(1)、bean管理—两个操作

A.Spring创建对象----Ioc
B.Spring注入属性----DI

(2)bean管理操作—两种方法

A.基于xml配置文件方法实现

a.set方法

Book.java

package com.pojo;

public class Book {
	
	// 创建属性
	private String bname;
	private String bauthor;
	// 创建set方法
	public void setBname(String bname) {
		this.bname = bname;
	}
	public void setBauthor(String bauthor) {
		this.bauthor = bauthor;
	}
	@Override
	public String toString() {
		return "Book [bname=" + bname + ", bauthor=" + bauthor + "]";
	}
	

}

配置xml

<!-- 2、set方法注入属性 -->
	<bean id="book" class="com.pojo.Book">
		<!-- Property name:表示类里的属性名称, value:表示向属性注入的值 -->
		<property name="bname" value="java"></property>
		<property name="bauthor" value="小和尚"></property>
	</bean>

测试类

// 2、测试set方法注入属性
	@Test
	public void setTest() {
		// 1加载spring的配置文件
		ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

		// 获取配置创建的对象
		Book book = context.getBean("book", Book.class);
		System.out.println(book);
	}

结果:
在这里插入图片描述

b.构造方法

Orders.java

package com.pojo;

public class Orders {
	
	// 属性
	private String oname;
	private String address;
	//有参构造方法
	public Orders(String oname, String address) {
		super();
		this.oname = oname;
		this.address = address;
	}
	@Override
	public String toString() {
		return "Orders [oname=" + oname + ", address=" + address + "]";
	}	

}

配置xml

<!-- 3、使用构造方法创建 -->
	<bean id="orders" class="com.pojo.Orders"> 
		<!-- name:类的属性名称, value:注入属性的值 -->
		<constructor-arg name="oname" value="彼岸花"></constructor-arg>
		<constructor-arg name="address" value="重庆"></constructor-arg>
	</bean>

测试类

// 3、构造方法注入
	@Test
	public void constructorTest() {
		// 1加载spring的配置文件
		ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

		// 获取配置创建的对象
		Orders orders = context.getBean("orders", Orders.class);
		System.out.println(orders);
	}

结果:
在这里插入图片描述

c.注入其他类型

(1)创建两个类 service 类和 dao 类
(2)在 service 调用 dao 里面的方法
(3)在 spring 配置文件中进行配置

UserDao.java

package com.service.dao;

public class UserDao {
	public void update() {
		System.out.println("update---dao");
	}
}

UserService.java
package com.service;

import com.service.dao.UserDao;

public class UserService {
	
	private UserDao userDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	public void add() {
		System.out.println("service add()..........");
		userDao.update();
	}

}

配置xml

<!-- 4、service和dao对象创建 -->
	<bean id="userService" class="com.service.UserService">
		<!-- 注入UserDao对象   name:类里的属性名称  ref: 创建userDao对象bean的id标签值 -->
		<property name="userDao" ref="userDaoImpl"></property>
	</bean>
	<bean id="userDaoImpl" class="com.service.dao.UserDao"></bean>

测试类

// 4、service和dao
	@Test
	public void serviceTest() {
		// 1加载spring的配置文件
		ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

		// 获取配置创建的对象
		UserService service = context.getBean("userService", UserService.class);
		service.add();
	}

结果:
在这里插入图片描述

d.注入内部bean

Emp.java

package com.pojo;

// 员工类
public class Emp {
	private String ename;
	private String gender;
	
	private Dept dept;

	public Dept getDept() {
		return dept;
	}

	public void setDept(Dept dept) {
		this.dept = dept;
	}

	public void setEname(String ename) {
		this.ename = ename;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	@Override
	public String toString() {
		return "Emp [ename=" + ename + ", gender=" + gender + ", dept=" + dept + "]";
	}		
	
}

Dept.java

package com.pojo;

public class Dept {
	private String dname;

	public void setDname(String dname) {
		this.dname = dname;
	}

	@Override
	public String toString() {
		return "Dept [dname=" + dname + "]";
	}
	
	

}

配置xml—配置类中的对象,在property中加bean

<!-- 5、内部bean注入 -->
	<bean id="emp" class="com.pojo.Emp">
		<!-- 设置两个普通属性 -->
		<property name="ename" value="json"></property>
		<property name="gender" value="nan"></property>
		<!-- 设置对象类型属性 -->
		<property name="dept">
			<bean id="dept" class="com.pojo.Dept">
				<property name="dname" value="后勤部"></property>
			</bean>
		</property>
	</bean>

测试类

// 5、bean内部注入
	@Test
	public void beanTest() {
		// 1加载spring的配置文件
		ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

		// 获取配置创建的对象
		Emp  emp = context.getBean("emp", Emp.class);
		System.out.println(emp);
	}

结果:
在这里插入图片描述

e.注入属性----级联赋值

配置xml

	<!-- 6、注入属性,级联赋值 -->
	<bean id="emp2" class="com.pojo.Emp">
		<property name="ename" value="lucy"></property>
		<property name="gender" value="女"></property>
		<!-- 级联赋值 -->
		<property name="dept" ref="dept2"></property>
	</bean>
	<bean id="dept2" class="com.pojo.Dept">
		<property name="dname" value="售后部"></property>
	</bean>

测试类

// 6、bean内部注入---级联赋值
	@Test
	public void beanTest2() {
		// 1加载spring的配置文件
		ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

		// 获取配置创建的对象
		Emp emp = context.getBean("emp2", Emp.class);
		System.out.println(emp);

	}

结果:
在这里插入图片描述

f.注入集合属性

1、注入数组类型属性
2、注入 List 集合类型属性
3、注入 Map 集合类型属性
Stu.java

package com.collection;

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

public class Stu {
	
	// 1、数组类型属性
	private String[] courses;
	// 2、list 集合类型属性
	private List<String> list;
	// 3、map集合类型属性
	private Map<String, String> map;
	// 4、set集合类型属性
	private Set<String> set;
	public void setCourses(String[] courses) {
		this.courses = courses;
	}
	public void setList(List<String> list) {
		this.list = list;
	}
	public void setMap(Map<String, String> map) {
		this.map = map;
	}
	public void setSet(Set<String> set) {
		this.set = set;
	}
	@Override
	public String toString() {
		return "Stu [courses=" + Arrays.toString(courses) + ", list=" + list + ", map=" + map + ", set=" + set + "]";
	}
	
	
}

配置xml

<!-- 7、 注入集合属性 -->
<bean id="stu" class="com.collection.Stu">
	<!-- 数组类型属性注入 -->
	<property name="courses">
		<array>
			<value>java</value>
			<value>c++</value>
		</array>
	</property>
	<!-- list 类型属性注入 -->
	<property name="list">
		<list>
			<value>张三</value>
			<value>小</value>
		</list>
	</property>
	<!-- map类型属性注入 -->
	<property name="map">
		<map>
			<entry key="JAVA" value="java"></entry>
			<entry key="PHP" value="php"></entry>
		</map>
	</property>
	<!-- set 类型属性注入 -->
	<property name="set">
		<set>
			<value>Mysql</value>
			<value>oracle</value>
		</set>
	</property>
</bean>

测试类

// 7、集合注入属性
	@Test
	public void collectionTest() {
		// 1加载spring的配置文件
		ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

		// 获取配置创建的对象
		Stu stu = context.getBean("stu", Stu.class);
		System.out.println(stu);
		
	}

结果:
在这里插入图片描述

4、设置对象类型
Course.java

package com.collection;

public class Course {
	private String cname;

	public void setCname(String cname) {
		this.cname = cname;
	}

	@Override
	public String toString() {
		return "Course [cname=" + cname + "]";
	}
	
}

Stu.java

// 学生所学多门课程
private List<Course> courseList;

public List<Course> getCourseList() {
	return courseList;
}
public void setCourseList(List<Course> courseList) {
	this.courseList = courseList;
}

配置xml

<!-- 8、设置对象类型 -->
<!-- 注入list 集合类型,值是对象 -->
<bean id="stu2" class="com.collection.Stu">
	<property name="courseList">
		<list>
			<ref bean="course1"/>
			<ref bean="course2"/>
		</list>
	</property>
</bean>
<bean id="course1" class="com.collection.Course">
	<property name="cname" value="spring5 框架"></property>
</bean>
<bean id="course2" class="com.collection.Course">
	<property name="cname" value="Mybatis 框架"></property>
</bean>

测试类

// 8、设置对象类型
@Test
public void classTest() {
	// 1加载spring的配置文件
	ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

	// 获取配置创建的对象
	Stu stu = context.getBean("stu2", Stu.class);
	System.out.println(stu.getCourseList());

}

结果:
在这里插入图片描述

5、提取集合注入部分
在配置空间引入空间名util

<?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"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">

Books.java

package com.collection;

import java.util.List;

public class Books {
	
	private List<String> list;

	public void setList(List<String> list) {
		this.list = list;
	}
	
	public void test() {
		System.out.println(list);
	}
	

}

配置xml

<!-- 9、使用util标签完成list集合注入提取 -->
<!-- 1、提取list集合的属性注入 -->
<util:list id="bookList">
	<value>java-pdf</value>
	<value>php-pdf</value>
	<value>c++-pdf</value>
</util:list>
<!-- 2、提取list集合类型属性注入使用 -->
<bean id="books" class="com.collection.Books">
	<property name="list" ref="bookList"></property>
</bean>

测试类

// 9、util完成list注入
	@Test
	public void utilTest() {
		// 1加载spring的配置文件
		ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

		// 获取配置创建的对象
		Books books = context.getBean("books", Books.class);
		books.test();
	}

结果:
在这里插入图片描述

g.BeanFactory操作bean

传入工厂名,返回产品对象

1、Spring 有两种类型 bean,一种普通 bean,另外一种工厂 bean(FactoryBean) 

2、普通 bean:在配置文件中定义 bean 类型就是返回类型
3、工厂 bean:在配置文件定义 bean 类型可以和返回类型不一样 
第一步 创建类,让这个类作为工厂 bean,实现接口 FactoryBean 
第二步 实现接口里面的方法,在实现的方法中定义返回的 bean 类型

Author.java – 实现FactoryBean

package com.factorybean;

import org.springframework.beans.factory.FactoryBean;

import com.pojo.Book;

public class Author implements FactoryBean<Book> {
	
	private Book book;

	@Override
	public Book getObject() throws Exception {
		Book book = new Book();
		book.setBname("java-pdf");
		return book;
	}

	@Override
	public Class<?> getObjectType() {
		// TODO Auto-generated method stub
		return null;
	}
	
	

}

配置xml

<!-- 10、 FactoryBean操作bean -->
<bean id="author" class="com.factorybean.Author"></bean>

测试类:

// 10、beanFactory
@Test
public void beanFactoryTest() {
	// 1加载spring的配置文件
	ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

	// 获取配置创建的对象
	Book book = context.getBean("author", Book.class);
	System.out.println(book);
}

结果:
在这里插入图片描述

h.Bean的单例、多例

单例,全局作用域使用一个对象–地址相同
多例,每次使用对象都是新new一个对象出来
① 单例
Xml的配置

<bean id="author" class="com.factorybean.Author"></bean>

测试类

// 11、单例,多例
	@Test
	public void singleToManyTest() {
		// 1加载spring的配置文件
		ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

		// 获取配置创建的对象
		Book book = context.getBean("author", Book.class);
		Book book2 = context.getBean("author", Book.class);
		System.out.println(book==book2);
	}

结果:
在这里插入图片描述

② 多例----加上
配置xml

	<bean id="author" class="com.factorybean.Author" scope="prototype"></bean>

结果:

在这里插入图片描述

i.Bean的生命周期
1、生命周期 
(1)从对象创建到对象销毁的过程 
2、bean 生命周期 
(1)通过构造器创建 bean 实例(无参数构造) 
(2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法) 
(3)调用 bean 的初始化的方法(需要进行配置初始化的方法) 
(4)bean 可以使用了(对象获取到了) 
(5)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)

Orders.java

package com.factorybean;

public class Orders {
	private String name;

	//无参构造方法
	public Orders() {
		System.out.println("第一步--执行无参构造方法创建bean实例");
	}

	public void setName(String name) {
		this.name = name;
		System.out.println("第二步--调用set方法设置属性值");
	}
	
	// 执行初始化方法
	public void initMethod() {
		System.out.println("第三步--执行初始化方法");
	}

	// 创建执行销毁方法
	public void destroyMethod() {
		System.out.println("第五步--执行销毁方法");
	}


}

配置xml

<!-- 12、bean的生命周期 -->
<bean id="orders2" class="com.factorybean.Orders" 
		init-method="initMethod" destroy-method="destroyMethod">
	<property name="name" value="硬盘"></property>		
</bean>

测试类

// 12、bean的生命周期
	@Test
	public void lifeTest() {
		// 1加载spring的配置文件
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

		// 获取配置创建的对象
		Orders orders = context.getBean("orders2",Orders.class);
		System.out.println("第四步--" + orders);
		// 销毁
		context.close();
	}

结果:
在这里插入图片描述

j.Bean的后置处理器

MyBeanPost.java

package com.factorybean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPost implements BeanPostProcessor{
	
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("在初始化之前执行的方法");
		return bean;
	}
	
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("在初始化之后执行的方法");
		return bean;
	}

}

配置xml

<!-- 13、Bean的后置处理器 -->
<bean id="myBeanPost" class="com.factorybean.MyBeanPost"></bean>

结果:
在这里插入图片描述

k.xml自动装配

根据指定装配规则(属性名称或者属性类型),Spring 自动将匹配的属性值进行注入
两种方式,根据名称,根据类型

Employee.java

package com.factorybean;

public class Employee {
	
	private Department department;

	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

}

Department.java

package com.factorybean;

public class Department {
	
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Department [name=" + name + "]";
	}
	

}

配置xml

<!-- 14、xml自动装配 -->
<!-- byName -->
<bean id="employee" class="com.factorybean.Employee" autowire="byName"></bean>
<bean id="department" class="com.factorybean.Department">
	<property name="name" value="后勤部"></property>
</bean>
<!-- byType -->
<bean id="employee2" class="com.factorybean.Employee" autowire="byType"></bean>

测试类:

// 14、xml自动装配
	@Test
	public void xmlTest() {
		// 1加载spring的配置文件
		ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

		// 获取配置创建的对象
		Employee employee = context.getBean("employee2", Employee.class);
		System.out.println(employee.getDepartment());
	}

结果:
在这里插入图片描述

l.xml管理外部文件

jdbc.properties

prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/demo
prop.userName=root
prop.password=root

配置xml

<!-- 15、管理引入外部文件 -->
<!-- 引入外部属性文件 -->	
<context:property-placeholder location="classpath:com/factorybean/jdbc.properties"/>
<!-- 配置连接池 -->	
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
	<property name="driverClassName" value="${prop.driverClass}"></property>
	<property name="url" value="${prop.url}"></property>
	<property name="username" value="${prop.userName}"></property>
	<property name="password" value="${prop.password}"></property>
</bean>

测试类

// 15、外部文件
	@Test
	public void jdbcTest() throws SQLException {
		// 1加载spring的配置文件
		ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

		// 获取配置创建的对象
		DataSource dataSource = context.getBean("dataSource", DataSource.class);
		System.out.println(dataSource.getConnection());
	}

结果:
在这里插入图片描述

B.注解方式操作bean

a.什么是注解
(1)使用注解目的:简化 xml 配置
(2)mvc  
@Component  
@Service -------service
@Controller ----controller
@Repository ----dao
 * 上面四个注解功能是一样的,都可以用来创建 bean 实例

案例

package com.ann;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class AnnTest {

	@Test
	public void annTest() {
		// 1加载spring的配置文件
		ApplicationContext context = new ClassPathXmlApplicationContext("com/ann/bean1.xml");

		// 获取配置创建的对象
		UserService userService = context.getBean("userService", UserService.class);
		userService.add();
	}

}



package com.ann;

import org.springframework.stereotype.Component;

@Component(value="userService")
public class UserService {
	public void add() {
		System.out.println("service add()..........");
	}

}

配置xml

<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"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
 http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">


<!-- 开启包扫描 -->
<context:component-scan base-package="com.ann"></context:component-scan>
b.注解方式注入
@Autowired:
根据属性类型进行自动装配 
第一步 把 service 和 dao 对象创建,在 service 和 dao 类添加创建对象注解 
第二步 在 service 注入 dao 对象,在 service 类添加 dao 类型属性,在属性上面使用注解


@Qualifier:
根据名称进行注入 
这个@Qualifier 注解的使用,和上面@Autowired 一起使用 
//定义 dao 类型属性 
//不需要添加 set 方法 
//添加注入属性注解 
@Autowired //根据类型进行注入 
@Qualifier(value = "userDaoImpl1") //根据名称进行注入 
private UserDao userDao; 


@Resource:
可以根据类型注入,可以根据名称注入 
//@Resource //根据类型进行注入 
@Resource(name = "userDaoImpl1") //根据名称进行注入 
private UserDao userDao; 


@Value:
注入普通类型属性 
@Value(value = "abc") 
private String name;

SpringConfig.java

package com.ann;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {"com.ann"})
public class SpringConfig {
	
}

UserDao.java

package com.ann;

import org.springframework.stereotype.Repository;

@Repository
public class UserDao {
	
	public void update() {
		System.out.println("update---dao");
	}

}

UserService.java

package com.ann;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

@Service
public class UserService {
	
	@Resource
	private UserDao userDao;
	
	public void add() {
		userDao.update();
	}

}

DemoTest.java

package com.ann;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class DemoTest {
	
	@Test
	public void beanFactoryTest() {
		ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
		UserService userService = context.getBean("userService", UserService.class);
		System.out.println(userService);
		userService.add();
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值