Spring Bean Type

Spring IOC是Spring最重要也是最基础的两个特性之一(另外一个是AOP,现不在讨论)。Spring框架的实现控制反转(IoC)的原则,也被称为依赖注入(DI)。过程对象定义它们的依赖关系,也就是说,他们使用的其它对象,只能通过构造函数参数,参数工厂方法或对象实例上设置的属性构造或从工厂回来后的方法。然后容器注入这些依赖项时创建bean。这个过程从根本上是反,因此得名“控制反转(IoC),控制实例化bean本身或者它的位置依赖关系通过使用直接建设类,或者一个Service Locator模式等机制。

而创建Spring可以通过以下几种方式:

  • xml,这是Spring创建Bean最早的一种方式
  • annotation,因为xml创建bean需要配置很多配置文件,Spring为了简化操作,所以在2.5以后支持以注解的形式来创建bean.
  • class,后面提倡元数据编程,因为在annotation中不可避免的还是需要使用xml,所以在spring3.0以后,可以使用@Configration,@Bean的类注解的形式来创建Spring bean.
  • properties,yml,在最新的Spring当中可以使用properties以及yml文件来创建bean.

1、xml bean

这是从Spring最开始就支持的一种bean的配置方式。
定义实体类:

User.java,用户类,拥有简单属性int,String类型以及复杂的对象引用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>

测试类:

@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>

测试类:

@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

通过Class来定义Bean对象。

@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();
    }

}

测试类:

@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配置文件
java
spring.properties.bean.age=20
spring.properties.bean.name=美女

定义实体类,并通过@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启动类:并通过@EnableConfigurationProperties指定可以使用properites来实例化bean的对象类型。

@SpringBootApplication
@EnableConfigurationProperties(Woman.class)
public class SpringBootRunner {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootRunner.class, args);
    }

}

测试类:

@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());
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值