Spring (依赖注入)

来源:互联网 发布:windows图标 编辑:程序博客网 时间:2024/05/05 20:36
     下面是配置文件,配置了spring的扫描路径,不配置这个注解不起作用。 
Java代码  收藏代码
  1. package com.expect.oa.config;  
  2.   
  3. import org.springframework.context.annotation.ComponentScan;  
  4. import org.springframework.context.annotation.Configuration;  
  5.   
  6. @Configuration  
  7. @ComponentScan("com.expect.oa.*")  
  8. //@ComponentScan(basePackages={"com.expect.oa.DI.*","com.expect.oa.DI2.*"})  
  9. //多个包可以这样写,这相当于在XML里配置了自动扫描  
  10. public class SpringConfig {  
  11.   
  12. }  

     这是一个接口: 
Java代码  收藏代码
  1. package com.expect.oa.DI.interfaces;  
  2.   
  3. public interface InterA {  
  4.   
  5.     void action1 ();  
  6.       
  7. }  

     下面声明一个简单的类,继承了上面的借口: 
Java代码  收藏代码
  1. package com.expect.oa.DI;  
  2.   
  3. import org.springframework.stereotype.Component;  
  4.   
  5. import com.expect.oa.DI.interfaces.InterA;  
  6.   
  7. @Component("interAImpl")  
  8. //@Named("interAImpl")同样的效果  
  9. public class CompA implements InterA{  
  10.   
  11.     @Override  
  12.     public void action1() {  
  13.         // TODO Auto-generated method stub  
  14.         System.out.println("spring DI");  
  15.     }  
  16.   
  17. }  

     下面是测试代码: 
Java代码  收藏代码
  1. package com.expect.oa.test;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.junit.Test;  
  6. import org.junit.runner.RunWith;  
  7. import org.springframework.test.context.ContextConfiguration;  
  8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  9.   
  10. import com.expect.oa.DI.interfaces.InterA;  
  11. import com.expect.oa.config.SpringConfig;  
  12.   
  13. @RunWith(SpringJUnit4ClassRunner.class)  
  14. @ContextConfiguration(classes = {SpringConfig.class})  
  15. public class TestSpringDI {  
  16.   
  17.     //个人建议给每个组件都起名。  
  18.     @Resource(name="interAImpl")  
  19.     //@Autowired 同样的效果  
  20.     InterA aService;  
  21.       
  22.     //这里是测试依赖注入  
  23.     @Test  
  24.     public void testDI() {  
  25.         aService.action1();  
  26.     }  
  27.   
  28. }  

获取【下载地址】   【免费支持更新】
三大数据库mysql  oracle  sqlsever   更专业、更强悍、适合不同用户群体
新录针对本系统的视频教程,手把手教开发一个模块,快速掌握本系统
A 集成代码生成器 [开发利器)+快速构建表单;
freemaker模版技术 ,0个代码不用写,生成完整的一个模块,带页面、建表sql脚本,处理类,service等完整模块
B 集成阿里巴巴数据库连接池druid;
  数据库连接池  阿里巴巴的 druid。Druid在监控、可扩展性、稳定性和性能方面都有明显的优势
C集成安全权限框架shiro ;
  Shiro 是一个用 Java 语言实现的框架,通过一个简单易用的 API 提供身份验证和授权,更安全,更可靠
D 集成ehcache 分布式缓存 ;
  是一个纯Java的进程内缓存框架,具有快速、精干等特点,广泛使用的开源Java分布式缓存。
E 集成微信接口开发;    F 图片爬虫技术;   G  SQL 编辑器, 支持复杂sql语句,生成报表,可以导出excel
H websocket及时通讯技术(即时聊天、及时站内信并声音提醒、实时在线管理、websocket及时刷新页面);


0 0
原创粉丝点击