Java Spring 自动装配
如果被注入的属性类型是Bean引用的话,那么可以在<bean>标签中使用autowire属性去配置自动注入方式,属性值有两个
- byName:通过属性名自动装配,即去匹配setXxx与id="xxx"(name="xxx")是否一致;
- byType:通过Bean的类型从容器中匹配,匹配出多个相同Bean类型,报错。
beans.xml
<bean class="org.example.UserDaoImpl" id="userDao"/>
<bean class="org.example.UserServiceImpl" id="userService" autowire="byName"/>
<bean class="org.example.UserServiceImpl" id="userService1" autowire="byType"/>
UserService
public interface UserService {
public void show();
}
UserServiceImpl
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
@Override
public void show() {
System.out.println(userDao);
}
}
主函数调用
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
((UserService) applicationContext.getBean("userService")).show();
((UserService) applicationContext.getBean("userService1")).show();
}
执行结果
org.example.UserDaoImpl@1f0f1111
org.example.UserDaoImpl@1f0f1111
如果xml文件自动装配中有多个同类型的bean容器将会报错
例如:
<bean class="org.example.UserDaoImpl" id="userDao"/>
<bean class="org.example.UserDaoImpl" id="userDao1"/>
<bean class="org.example.UserServiceImpl" id="userService" autowire="byName"/>
<bean class="org.example.UserServiceImpl" id="userService1" autowire="byType"/>
IDEA报错提示
无法自动装配。存在多个 'UserDao' 类型的 Bean。Bean: userDao1,userDao。属性: 'userDao'
运行结果提示
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService1' defined in class path resource [beans.xml]: Unsatisfied dependency expressed through bean property 'userDao'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.example.UserDao' available: expected single matching bean but found 2: userDao,userDao1
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService1' defined in class path resource [beans.xml]: Unsatisfied dependency expressed through bean property 'userDao'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.example.UserDao' available: expected single matching bean but found 2: userDao,userDao1
评论 (0)