1.创建maven项目
pom.xml中导入Spring依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.13</version>
</dependency>
2.创建实体类
package com.yy.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Goods {
private String goodID;
private String goodName;
private String goodType;
//品牌ID
private String brandID;
private BigDecimal cost;
private String providerID;
public Goods(String goodID, String goodName) {
this.goodID = goodID;
this.goodName = goodName;
}
}
3.配置文件
在resource文件夹下新建ApplicationContext.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="goods" class="com.yy.pojo.Goods">
<property name="goodName" value="主板"></property>
</bean>
</beans>
- bean:通过配置bean将实体类对象交给Spring容器
- id:给被管理的对象命名
- class:被管理对象的全限定名
- scope(进阶):默认singleton即为单利模式,就是在Spring容器中只存在一个的实例。
- property:通过Set方法进行依赖注入
- 依赖注入常用的两种:1.set方法注入。2.构造函数注入。
- 另外两种(了解)p命名和c命名空间注入:不能直接使用,需导入xml约束。
<bean id="goods" class="com.yy.pojo.Goods">
<!-- <property name="goodName" value="主板"></property>-->
<constructor-arg name="goodID" value="z001"></constructor-arg>
<constructor-arg name="goodName" value="主板"></constructor-arg>
</bean>
4.测试类
import com.yy.pojo.Goods;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class yyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("AplicationContext.xml");
Goods goods = (Goods) context.getBean("goods");
System.out.println(goods.getGoodName());
}
}