Spring 注解 小例子

本文介绍了使用Spring框架配置和实现依赖注入的过程,包括配置文件、接口定义、实现类、服务接口及其实现,以及测试类如何获取并使用依赖服务。

 

说明:此方法属于转载

 

1、配置

<?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-3.0.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
         
    <context:annotation-config/>    
    <!-- action暂未用注解 -->    
    <bean id="myAction" class="com.demo.annotation.action.MyAction" scope="prototype" />  
      
    <!-- 注解测试   -->  
    <context:component-scan base-package="com.demo.annotation.action" />  
        
</beans>  


 

 2、TestDao

         

public interface TestDao {
	
	 /** 
     * 得到dao层注解 
     * @return 
     */       
    public String getTestDaoAnnotation();

}


3、testDao实现类

 

@Repository("testDao")      
public class TestDaoImpl implements TestDao{

	public String getTestDaoAnnotation() {  
        // TODO Auto-generated method stub  
        return "This is testDao Annotation...";  
    }  
}


4、TestService 接口

public interface TestService {

	 public String getTestAnnotation();
	
}


5、TestService接口实现

 

@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;  
    }  
  
  
    public String getTestAnnotation() {  
    
        return testDao.getTestDaoAnnotation();  
    }  

}

6、测试类  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;  
    }  

}


 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值