Spring@autowired注解

Spring@autowired注解

第一步:

我们先要有一个类,在这个类中定义几个方法

代码如下:

package com.huweiyang;

publicclassA {

   public A(){

     System.out.println("我是A类的构造方法");

   }

   publicvoid add(){

     System.out.println("我是A类的add方法");

   }

}

第二步:

我们要有一个bean,Spring容器就是用来管理bean的所以他使用的注解也离不开bean,在bean中定义一个A类类型的变量,并给它set和get方法

代码如下:

package com.huweiyang;

 

import org.springframework.beans.factory.annotation.Autowired;

publicclassB {

   @Autowired

   private A a;

 

   public A getA() {

     a.add();

     returna;

   }

 

   publicvoid setA(A a) {

     this.a = a;

   }

}

第三步:

我们需要来配置xml,因为我们使用了@autwired注解的方式来注入,而spring中不支持自动注解的注入的功能,所以我们需要在xml文件中启动注解的功能并指定路径。

启动注解功能的属性是:<context-annotation-config/>

代码如下:

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

     http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.3.xsd">

    

<!--    启动注解功能 -->

     <context:annotation-config />   

   <bean id="aclass" class="com.huweiyang.A"></bean>

   <bean id="bcalss" class="com.huweiyang.B"></bean>

</beans>

 

第四步:

完成了上面的操作我们需要来测试功能是否完成,是否有用,所以我们要编写一个测试类来测试我们的代码我可以通过   new classpathxmlapplictionContext(),来读取xml文件

代码如下:      

package com.huweiyang;

 

import org.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Mapping {

 

       public static voidmain(String[] args) {

             

              ApplicationContextobj = new ClassPathXmlApplicationContext("beans.xml");

             

              B sr = (B)obj.getBean("bcalss");

             

              sr.getA();

       }

 

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值