IOC是什么?有什么作用?请写出5个相关案例代码
时间: 2023-04-06 11:02:27 浏览: 104
Ioc模式例子
IOC是Inversion of Control的缩写,即控制反转。它是一种设计模式,用于解耦组件之间的依赖关系,提高代码的可维护性和可扩展性。
以下是5个相关案例代码:
1. Spring框架中的IOC容器:
```
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) context.getBean("userService");
```
2. Struts2框架中的IOC容器:
```
<bean id="userService" class="com.example.UserService"></bean>
<bean id="userAction" class="com.example.UserAction">
<property name="userService" ref="userService"></property>
</bean>
```
3. Hibernate框架中的IOC容器:
```
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="packagesToScan" value="com.example"></property>
</bean>
```
4. Java EE中的EJB容器:
```
@Stateless
public class UserServiceImpl implements UserService {
@PersistenceContext
private EntityManager entityManager;
}
```
5. Android中的IOC框架ButterKnife:
```
@BindView(R.id.username)
EditText usernameEditText;
@BindView(R.id.password)
EditText passwordEditText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
}
```
阅读全文