Spring IOC 是 Spring 最重要也是最基礎(chǔ)的兩個(gè)特性之一(另外一個(gè)是 AOP 僻造,現(xiàn)不在討論)。Spring 框架的實(shí)現(xiàn)控制反轉(zhuǎn)(IoC)的原則邻遏,也被稱為依賴注入(DI)滴须。過(guò)程對(duì)象定義它們的依賴關(guān)系,也就是說(shuō),他們使用的其它對(duì)象,只能通過(guò)構(gòu)造函數(shù)參數(shù),參數(shù)工廠方法或?qū)ο髮?shí)例上設(shè)置的屬性構(gòu)造或從工廠回來(lái)后的方法。然后容器注入這些依賴項(xiàng)時(shí)創(chuàng)建bean朽合。這個(gè)過(guò)程從根本上是反,因此得名“控制反轉(zhuǎn)(IoC),控制實(shí)例化 bean 本身或者它的位置依賴關(guān)系通過(guò)使用直接建設(shè)類,或者一個(gè)Service Locator模式等機(jī)制俱两。
而創(chuàng)建 Spring 可以通過(guò)以下幾種方式:
-
xml
,這是Spring創(chuàng)建Bean最早的一種方式 -
annotation
,因?yàn)閤ml創(chuàng)建 bean 需要配置很多配置文件,Spring 為了簡(jiǎn)化操作,所以在2.5 以后支持以注解的形式來(lái)創(chuàng)建 bean. -
class
,后面提倡元數(shù)據(jù)編程,因?yàn)樵赼nnotation中不可避免的還是需要使用xml曹步,所以在spring3.0以后宪彩,可以使用@Configration,@Bean的類注解的形式來(lái)創(chuàng)建Spring bean. -
properties
,``yml ,在最新的 Spring boot 項(xiàng)目當(dāng)中可以使用properties以及yml文件來(lái)創(chuàng)建bean.
1、xml bean
這是從Spring最開(kāi)始就支持的一種bean的配置方式讲婚。
定義實(shí)體類:
User.java尿孔,用戶類,擁有簡(jiǎn)單屬性int,String類型以及復(fù)雜的對(duì)象引用Car.
public class User implements Serializable {
private int id;
private String name;
private Car car;
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 Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
}
Car.java
public class Car {
private String color;
private double price;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
配置文件:
<?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 id="user" class="com.segmentfault.spring.ioc.pogo.User">
<property name="id" value="1" />
<property name="name" value="carl" />
<property name="car" ref="car" />
</bean>
<bean id="car" class="com.segmentfault.spring.ioc.pogo.Car">
<property name="color" value="red" />
<property name="price" value="20000" />
</bean>
</beans>
測(cè)試類:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:xml-bean.xml"})
public class XmlBeanTest implements ApplicationContextAware {
private ApplicationContext context;
@Test
public void testXmlBean() {
User user = context.getBean(User.class);
Assert.assertEquals("Spring xml依賴注入失敗:" + user.getName(),"carl", user.getName());
Assert.assertEquals("Spring xml依賴注入失敗:" + user.getCar().getPrice(), "red", user.getCar().getColor());
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
}
2、注解類Bean
定義注解Bean.
@Component
public class Computer {
@Autowired
private User owner;
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
}
配置文件:
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.segmentfault.spring.ioc.beans.annotation" />
<bean class="com.segmentfault.spring.ioc.pogo.User" >
<property name="name" value="xiaomage" />
<property name="id" value="1" />
</bean>
</beans>
測(cè)試類:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:annotation-bean.xml"})
public class AnnotationBeanTest implements ApplicationContextAware {
private ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
@Test
public void testAnnotationBean() {
Computer computer = context.getBean(Computer.class);
Assert.assertEquals("Spring 注解注入失敗" + computer.getOwner().getName(),"xiaomage", computer.getOwner().getName());
}
}
3筹麸、Class類型的Bean
通過(guò)Class來(lái)定義Bean對(duì)象活合。
@Configuration
public class ClazzBeanConfig {
@Bean
public Computer computer(User user) {
Computer computer = new Computer();
computer.setOwner(user);
return computer;
}
@Bean
public User user(){
User user = new User();
user.setId(1);
user.setName("carl");
return user;
}
@Bean
public CustomBeanPostProcessor customBeanPostProcessor(){
return new CustomBeanPostProcessor();
}
}
測(cè)試類:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ClazzBeanConfig.class})
public class ClazzBeanTest implements ApplicationContextAware {
private ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
@Test
public void testClazzBean(){
Computer computer = context.getBean(Computer.class);
Assert.assertEquals("Spring class注入失敗","carl", computer.getOwner().getName());
}
}
4、properties bean
properties配置文件
spring.properties.bean.age=20
spring.properties.bean.name=美女
定義實(shí)體類竹捉,并通過(guò)@ConfigurationProperties注解指定在配置文件中的前綴芜辕。
@ConfigurationProperties(prefix = "spring.properties.bean")
public class Woman {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
工具類:
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static Object getBean(String name) throws BeansException {
if(context == null) {
throw new RuntimeException("context is null");
}
return context.getBean(name);
}
public static <T> T getBean(Class<T> requiredType) throws BeansException{
if(context == null) {
throw new RuntimeException("context is null");
}
return context.getBean(requiredType);
}
}
Spring boot啟動(dòng)類:并通過(guò)@EnableConfigurationProperties指定可以使用properites來(lái)實(shí)例化bean的對(duì)象類型。
@SpringBootApplication
@EnableConfigurationProperties(Woman.class)
public class SpringBootRunner {
public static void main(String[] args) {
SpringApplication.run(SpringBootRunner.class, args);
}
}
測(cè)試類:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {SpringBootRunner.class})
public class PropertiesBeanTest {
@Test
public void testPropertiesBean(){
Woman woman = ApplicationContextUtils.getBean(Woman.class);
Assert.assertEquals("Spring properties注入失敗" , 20, woman.getAge());
}
}