使用spring框架,通过spring容器来创建对象并使用
spring容器创建对象并使用的步骤如下:
第一,在pom.xml文件中配置spring框架
<!-- 加入springframework依赖-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.3</version>
</dependency>
第二步,配置spring.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">
<!--告诉spring创建对象
声明bean , 就是告诉spring要创建某个类的对象
id:对象的自定义名称,唯一值。 spring通过这个名称找到对象
class:类的全限定名称(不能是接口,因为spring是反射机制创建对象,必须使用类)
spring就完成 SomeService someService = new SomeServiceImpl();
spring是把创建好的对象放入到map中, spring框架有一个map存放对象的。
springMap.put(id的值, 对象);
例如 springMap.put("someService", new SomeServiceImpl());
一个bean标签声明一个对象。
-->
<bean id="studentOne" class="per.pcqstart.dao.impl.StudentDaoImpl"/>
<bean id="student" class="per.pcqstart.domain.Student"></bean>
<!--
spring能创建一个非自定义类的对象吗, 创建一个存在的某个类的对象。
-->
<!-- <bean id="mydate" class="java.util.Date" /> -->
</beans>
<!--
spring的配置文件
1.beans : 是根标签,spring把java对象成为bean。
2.spring-beans.xsd 是约束文件,和mybatis指定 dtd是一样的。
-->
第三步,创建相应类和接口
①创建student.java,
public class Student {
private Integer id;
private String studentNumber;
private String name;
private String subject;
private Integer score;
}
②studentDao.interface
public interface StudentDao {
public void sayHello();
}
③StudentDaoImpl.java
public class StudentDaoImpl implements StudentDao {
@Override
public void sayHello() {
System.out.println("hello ,l am springBuildObject!!!");
}
}
第四步,测试
//测试,使用spring容器创建StudentDaoImpl对象,并且使用该对象
@Test
public void test(){
//1、读取spring配置文件,从classes根路径开始搜索
String config = "spring.xml";
// 2.创建spring容器对象,就是ApplicationContext
// 在读取配置文件时,容器就通过无参构造方法创建了spring配置文件中所有的bean对象
// 在读取配置文件时,容器就通过无参构造方法创建了spring配置文件中所有的bean对象
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(config);
StudentDao studentOne = (StudentDao) ac.getBean("studentOne");
Student student = (Student) ac.getBean("studnent");
System.out.println(student);
studentOne.sayHello();
}