Spring自动注入

注意,注入的是bean标签下property的name与另一个beasn的id相同时,可以省略
例如当spring整合mybatis时

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>      
     	<property name="url" value="jdbc:mysql://localhost:3306/ssm"></property>
     	<property name="username" value="root"></property>
     	<property name="password" value="123456"/>
      </bean>
        <!-- 创建SqlSessionFactory对象 -->
      <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
      	<!-- 数据库连接信息来源于dataSource -->
      	<property name="dataSource" ref="dataSource"></property>
      	<property name="typeAliasesPackage" value="com.lee.pojo"></property>
      </bean>

在头文件中加入(default-autowire="byName"

factory中的第一个property的name的名字与第一个bean的id相同,所以这个property可以省略。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd"
         
        default-autowire="byName"
        >
  <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">      
      	<property name="typeAliasesPackage" value="com.lee.pojo"></property>
      </bean>

bean中加入


  <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean" autowire="byName">      
      	<property name="typeAliasesPackage" value="com.lee.pojo"></property>
      </bean>

byType

当property中name属性的累心与另一个bean类的class相同时,可以自动注入,但是当spring容器中有两个相同类型的bean类时,不能用byType

default

default表示此bean标签与头文件中的声明的autowire类型相同

constructor

本质上也是byName,但需要有对应属性的构造器,例如有一个类是两个基本属性,和一个外部类属性,需要单独创建一个只有外部类属性的构造器,总之,要自动注入哪些属性,就需要建立哪些属性的构造方法。

public class Teacher {
	private int age;
	private String name;
	private Student student;
	//省略set get方法
	public Teacher(Student student) {
		super();
		this.student = student;
	}

no

不自动注入

注解

在需要自动注入的属性前加入@Resource或@Autowired(注意要添加扫描含有注解的包)

@Resource (javax.annotation.Resource;)默认byName
@Autowired (org.springframework.beans.factory.annotation.Autowired;)默认byType

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值