[Spring]@Autowired 的使用

本文介绍如何在Spring中使用@Autowired注解实现依赖注入。通过在配置文件中加入<context:annotation-config>,可以在不编写setter方法的情况下自动装配Bean。文章提供了一个具体的示例,展示了配置文件的设置及带有@Autowired注解的类。
http://mydreams1983.blog.163.com/blog/static/8632879520095235322618/

要使用@Autowired 得在spring的配置文件里设置:

xmlns:context="http://www.springframework.org/schema/context "

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd ">

使用<context:annotation-config></context:annotation-config>之后就可以在类里设置@Autowired来自动绑定了。

实例如下:

1.配置文件:

<?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-2.0.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd ">
 <context:annotation-config></context:annotation-config>
 <bean id="auto123"  class="org.michael.spring.demo.autowire.AutoWireBean">
  <property name="name1" value="Jordan"></property>
 </bean>
 <bean id="auto"  class="org.michael.spring.demo.autowire.AutoWireBean" autowire-candidate="false">
  <property name="name1" value="Crystal"></property>
 </bean>
 <bean id="autowire1" class="org.michael.spring.demo.autowire.AutoWireBean2" >
  <property name="helloWord" value="Michael"></property>
 </bean>
 
</beans>

2.AutoWireBean2

package org.michael.spring.demo.autowire;

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

public class AutoWireBean2 {
 
 private String helloWord; 
 @Autowired
 private AutoWireBean auto;
 public String getHelloWord() {
  return helloWord;
 }
 public void setHelloWord(String helloWord) {
  this.helloWord = helloWord;
 }
 public AutoWireBean getAuto() {
  return auto;
 }
 
}

注意,这里的auto可以不用写set方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值