IOC和DI的xml和注解的方式分别怎么写?注解与XMl的对应关系是怎样的?如哪个注解等价于哪个xml配置
时间: 2023-06-26 18:06:45 浏览: 53
IOC和DI的XML方式:
在XML中,我们可以通过<bean>元素来定义一个Bean,并且可以在<property>元素中设置Bean的属性值。在程序中,我们可以通过使用ApplicationContext或BeanFactory来获取这些Bean。
示例代码如下:
```
<!-- 定义一个Bean -->
<bean id="userService" class="com.example.UserService">
<property name="userDao" ref="userDao"/>
</bean>
<!-- 定义另一个Bean -->
<bean id="userDao" class="com.example.UserDaoImpl"/>
<!-- 获取Bean -->
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
```
注解方式的IOC和DI:
在注解方式中,我们可以使用@Component、@Service、@Repository和@Controller等注解来标识一个Bean,并使用@Autowired注解来自动注入Bean。
示例代码如下:
```
@Service
public class UserService {
@Autowired
private UserDao userDao;
}
@Repository
public class UserDaoImpl implements UserDao {}
// 获取Bean
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);
```
注解与XML的对应关系如下:
- @Component/@Service/@Controller -> <bean>
- @Repository -> <bean> + <repository>
- @Autowired -> <property> + ref
- @Value -> <property> + value
例如,在注解方式中,@Component注解等价于XML配置中的<bean>元素。@Autowired注解等价于XML配置中的<property>元素和ref属性。