标签:
我想要使用注解的方式,在service层调用dao层查询数据库的方法,查询卡号“1”是否存在,可是报错:
这应该注解使用不成功的意思,spring注解应该怎么使用呢?
这里有个完整的例子,项目结构如下
TestAnnotation.java
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestAnnotation { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); MyAction action = (MyAction)context.getBean("myAction"); action.testAnnotation(); } }
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <context:annotation-config/> <!-- action暂未用注解 --> <bean id="myAction" class="com.demo.annotation.MyAction" scope="prototype" /> <!-- 注解测试 --> <context:component-scan base-package="com.demo.annotation" /> </beans>
MyAction.java
import javax.annotation.Resource; public class MyAction{ @Resource(name="testService") private TestService testService; public String testAnnotation(){ if(null == testService){ System.out.println("Service is null!!"); } String result = testService.getTestAnnotation(); System.out.println(result); return "success"; } public TestService getTestService() { return testService; } public void setTestService(TestService testService) { this.testService = testService; } }
TestService.java
public interface TestService { public String getTestAnnotation(); }
TestServiceImpl.java
import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; /** * * 注解测试 * */ @Service("testService") public class TestServiceImp implements TestService { /** * 自动装配 */ @Autowired @Qualifier("testDao") //@Resource(name="testDao"), 等价于<property ………… ref="testDao" /> private TestDao testDao; public TestDao getTestDao() { return testDao; } public void setTestDao(TestDao testDao) { this.testDao = testDao; } @Override public String getTestAnnotation() { // TODO Auto-generated method stub return testDao.getTestDaoAnnotation(); } }
TestDao.java
public interface TestDao { /** * 得到dao层注解 * @return */ public String getTestDaoAnnotation(); }
TestDaoImpl.java
import org.springframework.stereotype.Repository; /** * 测试Annotation * */ @Repository("testDao") public class TestDaoImpl implements TestDao { @Override public String getTestDaoAnnotation() { // TODO Auto-generated method stub return "This is testDao Annotation..."; } }
运行结果:
标签:
原文地址:http://www.cnblogs.com/gugibv/p/5723525.html