Spring学习-FactoryBean的使用

Spring的核心功能是管理bean的生命周期。需要使用一个bean时,只需要首先通过xml方式或者JavaConfig方式定义即可,之后使用@Autowired即可注入。

使用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"
         xsi:schemaLocation="http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
     <bean id="car" name="#car1" class="com.baobaotao.simple.Car"></bean>  
     <bean id="boss" class="com.baobaotao.simple.Boss"></bean>
</beans>

使用JavaConfig方式时,使用方式如下:

@Configuration
public class CarConfig{
 @Bean("car")
 public Car car(){
  return new Car();
 }
}

而除了直接使用bean定义方式以外,还有另一种方式,也就是通过工厂模式来生成对象。直接看代码:

package com.liguang.springboot.learn.beanAware;

import com.liguang.springboot.learn.beanAware.bean.Movie;
import org.springframework.beans.factory.FactoryBean;

public class MovieFactory implements FactoryBean<Movie>{

    @Override
    public Movie getObject() throws Exception {
        Movie movie = new Movie();
        movie.setFactoryName("factory Name");
        movie.printName();
        System.out.println("Producing bean from the factory bean!");
        return movie;
    }

    @Override
    public Class<?> getObjectType() {
        return Movie.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

FactoryBean是一个泛型类,通过实现FactoryBean接口,在getObject()方法当中,会生成所需要生产的对象。

之后在定义一个FactoryBean的bean,就可以使用@Autowired将其引入:

package com.liguang.springboot.learn.beanAware;

import com.liguang.springboot.learn.beanAware.bean.Movie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FactoryTest{

    @Bean("movie")
    public MovieFactory factory() {
        return new MovieFactory();
    }
}

package com.liguang.springboot.learn.beanAware;

import com.liguang.springboot.learn.beanAware.bean.Movie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BeanController {

    @Autowired
    Movie movie;

    @RequestMapping("test")
    public void test() {
        System.out.println(movie.getFactoryName());
    }
}

在上述例子当中,我们并没有直接定义一个Movie类型的bean,而是定义一个MovieFactory的bean,之后就可以直接使用Movie的bean,这正是FactoryBean的妙用。



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值