Spring详细创建流程如下
1)创建Maven工程
打开idea主界面
new Project ===> Name ==> Language ===> Maven ===> JDK ===> GroupId ===> Create
Src ===> 鼠标右键===>Delete
创建module
鼠标右键spring-demo ===> new ===> Module
new Module ===> Name ==> Language ==> Build System ===> Jdk ==>Create
2)导入依赖
<!--导入spring-context依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.12</version>
</dependency>
<!--导入测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
导入maven依赖
spring01下的pom.xml文件
3)创建MySrping.config
鼠标右击resourse文件 ===> new ===> XML ==> SpringConfig
<?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">
</beans>
4)创建Users类
package org.xiji;
/**
* 自定义类
*/
public class Users {
public void userInfo(){
System.out.println("userInfo");
}
}
5)编写MyConfig.xml文件的bean
<?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">
<!-- id 定义bean的id -->
<!-- class (包名+类名) 即Users类所在的路径 -->
<bean id="users" class="org.xiji.Users">
</bean>
</beans>
6)手动创建Users类
import org.junit.Test;
import org.xiji.Users;
public class CreateUsersByHandTest {
@Test
public void createUsers(){
System.out.println("通过手写创建");
Users users = new Users();
System.out.println(users);
users.userInfo();
}
}
测试结果
7)通过spring框架的ClassPathXmlApplicationContext 创建对象
new ClassPathXmlApplicationContext("加载指定配置类") ==> 加载bean
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.xiji.Users;
public class CreateUsersBySpringTest {
@Test
public void test(){
System.out.println("使用spring框架创建");
//通过xml文件创建对象 == > 加载指定的配置类
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("MyConfig.xml");
Users users = context.getBean("users", Users.class);
System.out.println(users);
users.userInfo();
}
}
测试结果
8)通过反射创建对象
通过java反射机制 Class.forName("类的全类名") ===> 获取构造器 ==》 实例化对象 ==》强转 ==》o.userInfo()
import org.junit.Test;
import org.xiji.Users;
public class CreateBeanByReflectTest {
/**
* 反射创建
* spring是通过反射创建类的
*/
@Test
public void createBeanByReflect() throws Exception {
System.out.println("通过反射创建");
//通过类的全路径创建类
Class aClass = Class.forName("org.xiji.Users");
/**
* 获取构造器,然后创建对象
*/
Users o = (Users) aClass.getDeclaredConstructor().newInstance();
System.out.println(o);
o.userInfo();
}
}
测试结果