《Java注释的使用》 author:heguikun 2010-11-9
1.@Resource
使用@Resource后免去了xml的代码,和类的get() set()方法
如下:
-----在Action中写法
import javax.annotation.Resource;//导入
public class PetAction extends DispatchAction {
@Resource private AllBiz allBiz=null;//找到合适类型注入
public ActionForward doCheckUserExists(ActionMapping mapping,ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws IOException {
String petName = request.getParameter("petName");//存在隐藏表单中
List list=allBiz.query("from PetInfo where petName='"+petName+"'");
System.out.println(list.size());
return null;
}
-----对于的Sping配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config /><!--表示打开注解-->
<bean name="/Petdiary" class="com.yourcompany.struts.action.DiaryAction"/><!--他根据这个Action找@Resourc-->
----以上就可以完成装配
如果想在xml中省去不写<bean name="/Petdiary" class="com.yourcompany.struts.action.DiaryAction"/>
请在这个类前加 :@Controller("/Petdiary") //表示这个类交个Spring管理import org.springframework.stereotype.Controller;
如果在某个类前加上:@Repository("别名") 这个类不需要在xml 出现,Spring也会自己找到并实例化
给需要该对象的类<context:component-scan base-package="com"/>//要在Xml中写这句话,叫它Spring扫描找到@Repository()
如下:
@Repository("allBiz")
public class AllBizImpl extends HibernateDaoSupport implements AllBiz {
}
xml中就不用出现<bean id="allBiz" class="com.aptech.jb.epet.biz.Impl.AllBizImpl"/>
但是@Repository("allBiz") 要和 @Resource 等配合使用,要么就不成功
2.
// @Autowired() @Qualifier("allBiz") 配合 跟 @Resource 效果一样 ,required=false意思是空也不抛出异常
@Autowired(required=false)
@Qualifier("allBiz")
private AllBiz allBiz;//get()set()方法都不用写
Java注释的使用
最新推荐文章于 2024-09-21 10:38:43 发布