以下是用Annotation的配置方式来实现简单Spring IOC
2013-05-13 15:02
162 查看
<!--第一步 配置aplicationContext文件--> <?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <context:component-scan base-package="com.tz.spring.entity"/> </beans>
package com.tz.spring.entity; import org.springframework.stereotype.Component; @Component//此标注声明将Cat放入容器中默认的id就是类名首字母小写,可以显示声明(value=” ”) public class Cat { private int id=200; private String name="黑猫"; public Cat(){ id=100; name="白猫"; } @Override public String toString() { return id+name; } }
package com.tz.spring.entity; import javax.annotation.Resource; import org.springframework.stereotype.Component; @Component public class User { private int id; private String name; @Resource//此标签声明对cat的引用,在默认情况下,会先匹配依赖的id //然后找属于Cat类型的依赖,如果没找到则什么都不做 //如果找到一个则直接赋值,如果找到多个则报错 private Cat cat; public User(){ id=110; name="小张"; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Cat getCat() { return cat; } public void setCat(Cat cat) { this.cat = cat; } @Override public String toString() { return id+name+cat; } }
第三步测试:从容器中拿出User的一个实例;
public void testcat(){ ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = (User)ac.getBean("user"); System.out.println(user); }
相关文章推荐
- 简单两步快速实现shiro的配置和使用,包含登录验证、角色验证、权限验证以及shiro登录注销流程(基于spring的方式,使用maven构建)
- struts2:lesson three:Annotation配置,实现request,session.application的四种方式,Result类型
- 天易47----Springmvc注解方式实现aop配置简单示例
- [置顶] Spring mvc通过xml配置文件方式实现简单HelloWorld
- 一个简单的基于注解的 Controller (spring 2.5 annotation 方式实现mvc )
- Spring Aop实现——Annotation方式(注解式)and Schema-based式(xml配置)
- spring AOP实现(Annotation方式/静态文件配置方式)
- Spring的简单实现实例(Spring的java配置方式)
- AOP之基于Annotation的零配置方式的实现
- spring 使用annotation替代xml配置实例(spring实现mail简单实现)
- 一个简单的基于注解的 Controller (spring 2.5 annotation 方式实现mvc )
- Spring Aop实现——Annotation方式(注解式)and Schema-based式(xml配置)
- 一个简单的基于注解的 Controller (spring 2.5 annotation 方式实现mvc )
- Linux下简单配置SAMBA服务,实现与Windows系统文件共享.
- 05 Spring Aop实例(AOP 如此简单)@Aspect、@Around 注解方式配置
- 每天学一点flash(57)简单抽奖方式实现
- 不用注册热键方式在Delphi中实现定义快捷键(又简单又巧妙,但要当前窗体处在激活状态)
- 用最简单的方式实现基于libevent框架的http client客户端
- 简单调用VS自带的数据源选择对话框实现数据库连接字符串配置
- 跨浏览器仿模式对话框的实现-集成方式最简单的在线Web编辑器(5分钟内完成集成)