叶千辰  

IOC 操作 Bean 管理(基于注解方式)


IOC:控制反转,把对象创建和对象之间的调用过程,交给 Spring 进行管理。
bean管理:Bean 管理指的是两个操作->Spring 创建对象、Spirng 注入属性。

1、什么是注解

(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值..)

(2)使用注解,注解作用在类上面,方法上面,属性上面

(3)使用注解目的:简化 xml 配置

 

 

准备工作:

  • 在spring4之后,想要使用注解形式,必须得要引入aop的包

  • 在配置文件当中,还得要引入一个context约束


    <?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
          http://www.springframework.org/schema/context/spring-context.xsd">
       
    </beans>

 

Bean的实现 :

我们之前都是使用 bean 的标签进行bean注入,但是实际开发中,我们一般都会使用注解!

1、配置扫描哪些包下的注解


<!--指定注解扫描包-->
<context:component-scan base-package="com.kuang.pojo"/>

2、在指定包下编写类,增加注解


@Component("user")
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
  public String name = "秦疆";
}

3、测试

posted on 2022-05-05 20:48  叶千辰  阅读(52)  评论(0)    收藏  举报