美文网首页我爱编程
Spring 创建Bean的几种形式

Spring 创建Bean的几种形式

作者: carl_zhao | 来源:发表于2018-04-09 07:58 被阅读0次

    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 boot 项目当中可以使用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配置文件

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

    相关文章

      网友评论

        本文标题:Spring 创建Bean的几种形式

        本文链接:https://www.haomeiwen.com/subject/itrbhftx.html