spring中几个注入注解的作用:
@Resouce @Autowired @Qualifier 这几个怎么用我就不说了,在各自用法中已经整合,现在主要讲这几个注解的作用。
-
第一点:控制反转 DI依赖注入(很简单的有个enity实体类,然后在mapper.xml文件中定义一个bean 定义id 定义class路径,在test中就能获取到 注入到该实体类得到值) 不过这种在实际操作中不常用。
-
` /使用上下文对象获取bean/
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:application.xml"); /*通过id 获取student*/ Student student= (Student) applicationContext.getBean("Student"); System.out.println("Student:"+student); // 控制反转:程序自己不创建对象,将创建对象的权力给容器,程序只负责获取`
- 第二点:测试的时候,用到了@Controller注解 意思就是在controller层创建了一个假数据。当需要调用service,dao,controller层的时候,需要用到ref (引用,依赖)。 但是当写了注入注解,就不需要再写这个代码了,直接把注解加在所需要定义的类型上边。
<!-- 声明一个studentService 实现类 并且通过 <property ref="studentDao" 根据id获取容器中已经声明bean -->
<bean id="studentService" class="com.aaa.service.Impl.IStudentServiceImpl"> <!--两个类相同,id不同-->
<property name="iStudentDao" ref="studentDao11111"/>
</bean>
<!-- 验证id 声明一个studentService1 实现类 并且通过 <property ref="studentDao" 根据id获取容器中已经声明bean -->
<!-- <bean id="studentService1" class="com.aaa.service.Impl.IStudentServiceImpl"> //两个类相同,id不同
<property name="iStudentDao" ref="studentDao11111"/>
</bean>
-->
<!-- 声明一个studentDao 接口对应的实现类的实例 -->
<bean id="studentDao11111" class="com.aaa.dao.impl.IStudentDaoImpl"></bean> <!-- 声明一个studentService 实现类 并且通过 <property ref="studentDao" 根据id获取容器中已经声明bean -->
<bean id="studentService" class="com.aaa.service.Impl.IStudentServiceImpl"> <!--两个类相同,id不同-->
<property name="iStudentDao" ref="studentDao11111"/>
</bean>
<!-- 验证id 声明一个studentService1 实现类 并且通过 <property ref="studentDao" 根据id获取容器中已经声明bean -->
<!-- <bean id="studentService1" class="com.aaa.service.Impl.IStudentServiceImpl"> //两个类相同,id不同
<property name="iStudentDao" ref="studentDao11111"/>
</bean>
-->
<!-- 声明一个studentDao 接口对应的实现类的实例 -->
<bean id="studentDao11111" class="com.aaa.dao.impl.IStudentDaoImpl"></bean>
/*根据id 获取bean*/
IStudentService studentService = (IStudentService) applicationContext.getBean("studentService");
/* 不同的id */
/*IStudentService studentService1 = (IStudentService) applicationContext.getBean("studentService1");*/
/*根据类型获取bean , 如果容器中有两个相同类型的bean, 只能通过id 进行获取 */
//
IStudentService iStudentService2 = applicationContext.getBean(IStudentService.class);
Student student1 = iStudentService2.findAllStudentById(1);
System.out.println("Student3:"+student1);
@Component @Controller @Service @Repository,生成实例,并装配
@Autowired @Resource
@Component @Servicec @Repository @Controller 生成实例的注解
很简单的概念,就是在通过注解的形式时,在开启注解的情况下 能被idea自动识别为 service,dao,controller。