您的位置:首页 > 编程语言 > Java开发

以下是用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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐