日期:2014-05-17  浏览次数:20581 次

spring的注解注入问题。。。。。。。
@Autowired 默认按类型装配,在spring中去找与类型匹配的bean,怎样算是匹配啊?
package cn.itcast.service.impl;

import cn.itcast.dao.PersonDao;
import cn.itcast.service.PersonService;

public class PersonServiceBean implements PersonService {
@Autowired//注解
private PersonDao personDao;

public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}

public void save(){
personDao.add();
}
}

beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"  
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
   
  <context:annotation-config/>
   
  <bean id="personDao" class="cn.itcast.dao.impl.PersonDaoBean"></bean>//找到匹配的bean
</beans>

------解决方案--------------------
@Autowired 默认按类型装配

比如:你有一個接口,接口有一個實現類,那麽只有這個實現類注入給這個接口,才是類型匹配,否則報錯。
如果這個接口有多個實現類,也會報錯。因為,他們的類別是一樣的,spring無法確定要具體注入哪一個。
所以,一般會結合 按照name 和按照類別注入。
------解决方案--------------------
@Autowired()是按类型匹配的,如果加上@Qualifier("BEAN名称")就变为按名称匹配
其实用@Resource("bean名称")更好
------解决方案--------------------
类型匹配 PersonDaoBean实现了PersonDao 这个接口
------解决方案--------------------
@Resource(name="")

业务逻辑层:
@Component("ztreeBiz")
public class ZtreeBizImpl{} //biz接口实现因
@Resource(name="ztreeDao")
public ZtreeBiz ztreeBiz;
数据访问层:
@Component("ztreeDao")
public class ZtreeDaoImpl.... {}
Action 同样可以在加上一个原型
@Scope("prototype")
------解决方案--------------------
同样在学习eclipse+SSH+注解.会了记得教我噢。
------解决方案--------------------
我现在查询数据库多个表内容,把大部分东西封装到一个bean里,注解@table应该怎么写?不写可以吗
------解决方案--------------------
@Autowired()是按类型匹配的,如果加上@Qualifier("BEAN名称")就变为按名称匹配
其实用@Resource("bean名称")更好
------解决方案--------------------
Spring的实现原理是这样的,你在配置文件中使用<bean>标签配置了cn.itcast.dao.impl.PersonDaoBean,那么Spring容器就会完成对你这个类的生成、管理(我记得是放在一个Map里)。当在其他的地方使用这个实现类的接口(比如你这里是:PersonDao)来引用该接口的实现类对象。你这里是使用Autowired注解(也能使用XML),那么Spring容器就根据这个接口去找该接口的实现类对象,完成注入。而且如果使用了Autowired注解,默认情况下这个接口就必须只能有一个实现类,否则Spring容器就不知道该注入哪个实现了,会报错,这个时候就需要再Autowired注解中指出到底使用哪个实现类。当然了,注入的过程实际上是一个递归的过程(因为你依赖的实现类中也可能依赖其他接口的实现类对象)。总之,Spring容器必须先将这些类生成才能完成类和类之间关系的管理(引用关系)。原理就是这样,希望能帮助楼主理解,呵呵呵。