注解@Component

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

 

applicationContext.xml 

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

 使用:

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

指定多个包的三种方式:

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

简单类型属性赋值:

 引用类型赋值:

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

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

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

猜你喜欢

转载自blog.csdn.net/RreamigOfGirls/article/details/127004663
今日推荐