注意,注入的是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