一.Spring IOC/DI
1.新建spring项目 (java project类型)
2.准备好需要的jar包.SPRING系列教材 (一)- 教程,右上角有
3.导入包,前面的学习都已经会了
4.写一个pojo Category,用来演示IOC和DI
5.写applicationContext.xml配置文件
6.写一个测试类
运行:
没有问题
二.注入对象
跟上面的教程是相同的
写一个product.java
package com.how2java.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;
}
}
用ref注入另一个对象
<?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.how2java.pojo.Category">
<property name="name" value="category 1" />
</bean>
<bean name="p" class="com.how2java.pojo.Product">
<property name="name" value="product1" />
<property name="category" ref="c" />
</bean>
</beans>
测试
package com.how2java.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.how2java.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());
}
}
三.注解方式 IOC/DI
对注入对象行为的注解:
1.修改applicationContext.xml
在代码里添加
<context:annotation-config/>
表示Spring用注解的方式进行配置
2.添加@Autowired或者@Resource
bean对象本身也可以用注解的方式
修改applicationContext.xml,什么都去掉,只添加:
<context:component-scan base-package="com.how2java.pojo"/>
表示:告诉Spring,bean都放在com.how2java.pojo这个包下
为Category类加上@Component注解,表明此类是bean
package com.how2java.pojo;
import org.springframework.stereotype.Component;
@Component("c")
public class 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;
}
private int id;
private String name="category 1";
}
Product类同理
最后运行,运行结果是和上面的方式运行结果一样