完整代码:spring1.zip - 蓝奏云
将对象的创建权交给spring框架,我们再使用new创建对象。
我们使用idea和maven进行编译开发
1、导入spring相关的包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.12</version>
</dependency>
2、定义个Category类
package com.how2j.pojo;
public class Category {
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Category{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private int id;
private String name;
}
3、编写xml文件,设置java 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">
<bean name="c" class="com.how2j.pojo.Category">
<property name="id" value="1"/>
<property name="name" value="category 1"/>
</bean>
</beans>
4、测试spring
package test;
import com.how2j.pojo.Category;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
@Test
//spring的控制翻转
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml" );
Category c = (Category) context.getBean("c");
System.out.println(c);
}
}
注:目录结构如下: