Spring是一个基于IOC/DI结构的J2EE框架
IOC是控制反转,Spring容器帮我们自动创建对象
DI是依赖注入,Spring帮我们,将前端传来的值自动加载进Bean中对应字段中
代码
1、导入jar包
链接:https://pan.baidu.com/s/1wtBmbkGKWRNZb6bTyxK5Eg
提取码:op0j
2、写model
Category
package com.llhc.pojo;
public class Category {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Product
package com.llhc.pojo;
public class Product {
private int id;
private String name;
private Category category;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
3、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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean name="c" class="com.llhc.pojo.Category">
<property name="name" value="cateogry 1"></property>
</bean>
<bean name="p" class="com.llhc.pojo.Product">
<property name="name" value="product 1"/>
<property name="category" ref="c"/>
</bean>
</beans>
4、测试
package com.llhc.controller;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.llhc.pojo.Category;
import com.llhc.pojo.Product;
public class TestSpring {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
Product p=(Product) context.getBean("p");
System.out.println(p.getName());
System.out.println(p.getCategory().getName());
}
}
图片.png
网友评论