Component注解:把普通的POJO 类实例化到spring的IOC容器中,就是定义成<bean id="" class="">
项目目录树:
ApplicationContext.xml
<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-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" > <!-- component-scan 会自动开启bean自动注册,base-package会扫描该包下的特殊注解 --> <context:component-scan base-package="com.donghai.bean" /> </beans>
User.java
package com.donghai.bean; import org.springframework.stereotype.Component; @Component("user") //使用Component注解,相当于添加<bean id="user" class="com.donghai.bean.User" /> public class User { private String name = "ddh"; public String getName() { return name; } }
Group.java
package com.donghai.bean; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component("group") public class Group { @Autowired //使用自动装配,默认按照byType对应的类型查找bean,如果只有一个注入,如果有多个抛出异常
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type
需要使用@Qualifier(" ") 来指定使用那个实现
,也可以使用Resource(name="user") 使用资源指定 private User user; public User getUser() { return user; } }
Client.java
package com.donghai.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.donghai.bean.Group; import com.donghai.bean.User; public class Client { public static void main(String[] args){ ApplicationContext acc = new ClassPathXmlApplicationContext("applicationContext.xml"); Group group = (Group)acc.getBean("group"); System.out.println(group.getUser().getName()); } }
运行结果: