Spring的IOC注解方式实现

SpringIOC注解方式实现

maven所需依赖

       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-context</artifactId>
           <version>5.2.3.RELEASE</version>
       </dependency>
       <dependency>
           <groupId>aspectj</groupId>
           <artifactId>aspectjweaver</artifactId>
           <version>1.5.4</version>
       </dependency>

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
                http://www.springframework.org/schema/context/spring-context.xsd">
    
    
    <!--重要 : 要使用注解配置bean 必须开启spring注解支持-->
    <context:annotation-config/><!--开启注解支持-->

    <!--规定注解扫描器所扫描的包-->
    <context:component-scan base-package="my.xzb.pojo"/>
    
    

</beans>

环境准备

  • pojo
@Component//此注解将被扫描器扫描,并将此类加入IOC容器
@Scope()//用于指定此bean的作用域
public class User {
   @Value("你的名字是:红红")//此注解可用于属性上,或set方法上 用于给属性赋值
   private String userName;

   public void setUserName(String userName) {
       this.userName = userName;
   }

   public String getUserName() {
       return userName;
   }

   @Override
   public String toString() {
       return "User{" +
               "userName='" + userName + '\'' +
               '}';
   }

   public User() {
   }
   public User(String userName) {
       this.userName = userName;
   }
}
  • 测试类
public class Test {

    //测试注解方式是否成功将User实体类加入了IOC容器
    public static void main(String[] args) {
        //
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");

        User user = ac.getBean("user", User.class);//beand的id就是 注解所在类的类名首字母小写 例:User->user

        System.out.println(user);
    }

}

//结果:  User{userName='你的名字是:红红'}

注意:

  • @Autowired :自动装配通过类型。名字如果Autowired不能唯一 自动装配上属性,则需通过@Qualifier(value=" xxx")
  • @Nullable :字段标记 了这个注解,说明这个字段可以为nu1l;
  • @Resource : 自动装配通过名字。类型。
  • @Component :组件,放在类上,说明这个类被Spring管理了,就是bean!
  • @Component 衍生注解用于不同层级 但功能相同(放在类上,说明这个类被Spring管理了,就是bean)

    dao > @Repository

    service > @Service

    controller > @Controller

  • @Scope() :用于指定此bean的作用域
  • @Value(“你的名字是:红红”) :此注解可用于属性上,或set方法上 用于给属性赋值
  • 两种方式对比:
  • xml:配置繁琐,但理解容易且万能,维护简单…
  • 注解:配置简单但维护难…
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值