Spring全家桶笔记八:依赖注入与Bean管理

Spring全家桶笔记八:依赖注入与Bean管理

依赖注入方式

构造器注入

1
2
3
4
5
6
7
8
9
10
@Service
public class OrderService {
private final UserService userService;
private final OrderDao orderDao;

public OrderService(UserService userService, OrderDao orderDao) {
this.userService = userService;
this.orderDao = orderDao;
}
}

Setter注入

1
2
3
4
5
6
7
8
9
@Service
public class PaymentService {
private PaymentGateway paymentGateway;

@Autowired
public void setPaymentGateway(PaymentGateway paymentGateway) {
this.paymentGateway = paymentGateway;
}
}

字段注入

1
2
3
4
5
@Service
public class OrderService {
@Autowired
private UserService userService;
}

Bean作用域

1
2
3
4
5
6
7
@Service
@Scope("prototype") // 多例
public class MyService {}

@Service
@Scope("request") // 请求作用域
public class RequestService {}

@Conditional条件装配

1
2
3
4
5
6
7
8
9
10
11
12
13
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
@Service
public class FeatureService {}

@ConditionalOnMissingBean(UserService.class)
@Bean
public UserService userService() {
return new UserService();
}

@ConditionalOnClass(RedisTemplate.class)
@Configuration
public class RedisConfig {}

Bean生命周期

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Component
public class MyBean implements InitializingBean, DisposableBean {

@PostConstruct
public void init() {
System.out.println("初始化");
}

@PreDestroy
public void destroy() {
System.out.println("销毁");
}

@Override
public void afterPropertiesSet() {}

@Override
public void destroy() {}
}

外部化配置

1
2
3
4
5
6
7
8
9
10
11
@Component
public class MyComponent {
@Value("${custom.property}")
private String property;

@Value("${db.url:localhost}")
private String dbUrl;

@Value("#{systemProperties['user.dir']}")
private String userDir;
}

总结

依赖注入是Spring核心特性,合理选择注入方式、配置Bean作用域、条件装配等是构建健壮应用的关键。