Spring得注解注入相关

传统的spring是采用得xml配置好很多需要注入得bean,然后在需要注入的类里面为注入对象声明(必须添加setter方法,不然会报错),如下:

bean.xml配置:


<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>         
<bean id="service" class="com.bai.springioc.service.Service">
     <property name="dao" ref="dao"></property>
</bean><!--注入到得类-->
      
<bean id="dao" class="com.bai.springioc.dao.Dao"><!--注入对象-->
        <property name="name" value="baiyongcheng2"></property><!--设置对象得值-->
        <property name="age" value="25"></property>
</bean>

service类:

public class Service {
	private Dao dao;

	public Dao getDao() {
		return dao;
	}

	public void setDao(Dao dao) {//必须添加的方法
		this.dao = dao;
	}
	public String toString() {
		return "name:"+dao.getName()+";age:"+dao.getAge();
	}
}

dao类:

public class Dao {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}

启动类:

public class Application {
	public static void main(String[] args){
		ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:bean.xml");
		Service service = (Service) ac.getBean("service");
		System.out.println(service);
	}
}

这种方式需要将所有需要得bean全部配置到xml里面,而且需要为需要注入得类得bean配置好属性得依赖,当存在大量得备案注入就会导致xml内容十分庞大,不利于开发,注解注入为开发带来的方便;

当使用注解注入上面这个例子就变成:

bean.xml:

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <!--开启注解(有很多种方式)-->
<bean id="service" class="com.bai.springioc.service.Service"></bean><!--不需要配置属性依赖-->
<bean id="dao" class="com.bai.springioc.dao.Dao">
        <property name="name" value="baiyongcheng"></property>
        <property name="age" value="25"></property>
</bean>

service

public class Service {
	@Autowired
	private Dao dao;//不许添加setter

	public String toString() {
		return "name:"+dao.getName()+";age:"+dao.getAge();
	}
}

dao和启动类一样;

这样子配置就很清爽了;

当需要需要以接口或者父类得类型注入时则需要注意了,如果一个接口存在多个实现类时继续使用上面的方法就无法匹配bean会产生报错,因为采用@Autowired注解进行注入时,默认是按照bean得java类型来进行匹配的,当不存在时就会报错(如果设置了require属性@Autowired(required=false)则不会报错返回一个null),当匹配到多个bean时就会按照属性名匹配bean得id匹配到则成功注入,否则就会出现报错。这点与@Resource注解相反,@Resource首先会按照名称匹配(如果按照名称匹配到bean但是类型不对就会报错,如果没有匹配到bean再按类型匹配)再按照类型匹配,同时可以设置name或者type。

猜你喜欢

转载自blog.csdn.net/qq_38836082/article/details/81811340