0


注解@Component

  1. 1@Component
  1. @Component: 创建对象的,等同于<bean>,属性:value 就是对象的名称,也就是beanid的值,value值是唯一的
  1. @Component(value = "myStudent") // 指定对象名称
  2. @Component("myStudent") // 省略value
  3. @Component // 不指定对象名称,由spring提供默认名称:类名首字母小写

applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  6. <!--声明组件扫描器-->
  7. <!-- 组件:Java对象-->
  8. <!-- component-scan工作方式: spring回扫描遍历base-package指定的包把包中和子包中的所有类,找到类中的注解 ,按照注解功能创建对象,
  9. 或给属性赋值 -->
  10. <context:component-scan base-package="com.example.ba01"></context:component-scan>
  11. </beans>

使用:

  1. String config = "applicationContext.xml";
  2. ApplicationContext ac = new ClassPathXmlApplicationContext(config);
  3. Student student = (Student) ac.getBean("myStudent");
  4. System.out.println(student);
  1. 1@Repository : (用于持久层的上面)放在DAO的实现类上面,表示创建DAO对象,DAO对象是能访问数据库的
  2. 2@Service: (用在业务层类的上面)创建Service对象,Service对象是做业务处理,可以有事务等功能
  3. 3@Controller : (用在控制器上) 创建控制器对象,能够接受用户提交的参数,显示请求的处理的结果

指定多个包的三种方式:

  1. <context:component-scan base-package="com.example.ba01"></context:component-scan>
  2. <context:component-scan base-package="com.example.ba02"></context:component-scan>
  3. <!--使用分隔符(;或,)分隔多个包名-->
  4. <context:component-scan base-package="com.example.ba01;com.example.ba02"></context:component-scan>
  5. <!--指定父包-->
  6. <context:component-scan base-package="com.example"></context:component-scan>

简单类型属性赋值:

引用类型赋值:

@Autowired: Spring 框架提供的注解,实现引用类型的赋值。spring中通过注解给引用类型赋值,使用的是自动注入原理,支持byName、byType

@Autowired:默认使用的是byType自动注入

  1. //byName 注解方式(@Autowired、@Qualifier无先后顺序)
  2. @Autowired(required = true)
  3. // required = true:表示引用类型赋值失败,程序报错并停止运行
  4. // required = true:表示引用类型赋值失败,程序正常运行,引用类型是null
  5. @Qualifier("mySchool")
  6. private School school;
标签: java spring mybatis

本文转载自: https://blog.csdn.net/RreamigOfGirls/article/details/127004663
版权归原作者 饮茶听风 所有, 如有侵权,请联系我们删除。

“注解@Component”的评论:

还没有评论