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

Spring系列【04】应用@Autowired注解实现Bean的注入

2014-12-14 12:02 671 查看
User.java

package cn.com.xf;

public class User {
private String name;
private int age;
private String remark;

//省略setter/getter方法

@Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", remark=" + remark
+ "]";
}

}


UserUtil.java

package cn.com.xf;
//注意引入此包
import org.springframework.beans.factory.annotation.Autowired;

public class UserUtil {
@Autowired   //自动装配
private User user;

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}

public boolean isUser() {
if (user != null) {
return true;
} else {
return false;
}
}

}


Spring.xml配置文件

<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">   <!--这个Bean注意了。。。-->
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor">
</bean>
<bean id="user" class="cn.com.xf.User">
<property name="name" value="jikoy"></property>
<property name="age" value="28"></property>
<property name="remark" value="this is remark245"></property>
</bean>
<bean id="userUtil" class="cn.com.xf.UserUtil"></bean>
</beans>


以上已经实现了自动装配功能,本节已对注解有了初步认识,后面我们将对注解进行全面的学习。

本节的测试类与前几节一样,后面的内容,我们重新定义类,老是User,大家都烦了吧!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: