您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Spring IOC有哪些知识点
## 一、IOC概念与核心思想
### 1.1 什么是IOC
IOC(Inversion of Control,控制反转)是Spring框架的核心思想之一,指将对象的创建、依赖关系的管理从程序代码中转移到外部容器中。传统编程模式下,对象A依赖对象B时需要在A内部显式创建B实例;而IOC模式下,容器负责创建B实例并注入到A中。
### 1.2 DI与IOC的关系
DI(Dependency Injection,依赖注入)是IOC的具体实现方式,通过以下三种主要形式:
- 构造器注入
- Setter方法注入
- 字段注入(不推荐)
### 1.3 设计模式体现
IOC本质是工厂模式与策略模式的结合体:
- 容器作为中央工厂管理所有Bean
- 通过策略决定依赖注入的具体方式
## 二、IOC容器体系结构
### 2.1 BeanFactory与ApplicationContext
```java
// BeanFactory基础功能示例
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans.xml"));
MyBean bean = factory.getBean(MyBean.class);
// ApplicationContext增强功能
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
特性 | BeanFactory | ApplicationContext |
---|---|---|
延迟初始化 | ✓ | × |
自动BeanPostProcessor注册 | × | ✓ |
国际化支持 | × | ✓ |
事件发布机制 | × | ✓ |
<!-- 典型bean定义 -->
<bean id="userService" class="com.example.UserServiceImpl">
<property name="userDao" ref="userDao"/>
<property name="timeout" value="5000"/>
</bean>
<!-- 自动装配示例 -->
<bean id="accountService" class="com.example.AccountService" autowire="byType"/>
@Component
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Value("${app.timeout}")
private int timeout;
}
@Configuration
@ComponentScan("com.example")
public class AppConfig {
@Bean
public DataSource dataSource() {
return new DruidDataSource();
}
}
@Configuration
@Import(OtherConfig.class)
@PropertySource("classpath:app.properties")
public class AppConfig {
@Bean(initMethod = "init", destroyMethod = "cleanup")
@Scope("prototype")
public ComplexBean complexBean() {
return new ComplexBean();
}
}
@Autowired
@Qualifier("mainDataSource")
private DataSource dataSource;
// 或使用JSR-330注解
@Inject
@Named("backupDataSource")
private DataSource backupSource;
<bean id="lazyBean" class="com.example.ExpensiveBean" lazy-init="true"/>
作用域 | 描述 |
---|---|
singleton | 默认作用域,容器中唯一实例 |
prototype | 每次获取都创建新实例 |
request | Web请求范围 |
session | Web会话范围 |
application | ServletContext生命周期 |
websocket | WebSocket会话范围 |
@Bean
@Conditional(ProdEnvCondition.class)
public Service prodService() {
return new ProductionService();
}
@Configuration
@Profile("development")
public class DevConfig {
@Bean
public DataSource devDataSource() {
return new EmbeddedDatabaseBuilder().build();
}
}
public class CustomBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
System.out.println("初始化前处理: " + beanName);
return bean;
}
}
public class TimerFactoryBean implements FactoryBean<Timer> {
@Override
public Timer getObject() {
return new Timer(true); // 创建守护线程Timer
}
@Override
public Class<?> getObjectType() {
return Timer.class;
}
}
Spring IOC作为框架基石,通过灵活的配置方式和强大的容器管理能力,实现了对象依赖关系的解耦。深入理解IOC核心原理和扩展机制,能够帮助开发者构建更灵活、可维护的应用程序。随着Spring Boot的普及,虽然显式配置减少,但底层仍然基于这些核心概念运作。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。