BeanFactory和FactoryBean

BeanFactory是Spring ioc容器的一个接口,用来获取以及管理Bean的依赖注入和生命周期

FactoryBean是一个接口,用来定义一个工厂Bean,它可以产生某种类型的对象。如果一个Bean实现了FactoryBean,你获取的时候不是直接返回Bean实例,而是返回FactoryBean中getObejct返回的对象,通常用于创建很复杂的对象

eg:复杂的对象:jedis客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Component("redisClient")
public class RedisClientFactoryBean implements FactoryBean<JedisPool> {

// 模拟配置,可以改成 @Value 注入 application.properties 里的值
private String host = "localhost";
private int port = 6379;

@Override
public JedisPool getObject() throws Exception {
System.out.println("初始化 Redis 连接池...");
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(10);
return new JedisPool(config, host, port);
}

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

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

使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class RedisService {

@Autowired
private JedisPool jedisPool; // 注意:注入的就是 getObject() 返回的 JedisPool

public String get(String key) {
try (Jedis jedis = jedisPool.getResource()) {
return jedis.get(key);
}
}

public void set(String key, String value) {
try (Jedis jedis = jedisPool.getResource()) {
jedis.set(key, value);
}
}
}