1在src下创建applicationcontext.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
在这配置bean
<bean name=" bean的名字在 后面创建对象时调用 " class= "com. 包到 类名" >
<property name="类.属性名" value=“预设值”>
< bean>
</beans>
2.Test.java
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.how2java.pojo.Category;
import com.how2java.pojo.Pro;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "applicationContext.xml" });
Category cc=(Category)context.getBean("c");
System.out.println(cc.getName());
Pro p = (Pro)context.getBean("p");
System.out.println(p.getName());
System.out.println(p.getCate().getName());
}
}
3.注解 简化applicationcontext.xml
3.1@Autowired
<context:annotation-config/>
可以把类中 的类对象 引用 去掉
在引用的类中 的声明 或者 set方法上 @Autowired,让其自动找到注入对象的类
等同在
<bean>
<property name="" ref=" bean.name">
</bean>
@Autowired
private Category category;
// 或者
@Autowired
public void setCategory(Category category) {
this.category = category;
}
**3.2@Resource
把 类对象 指向了在applicationcontext.xml中的bean 类
@Resource(name="c")
private Category category;
3.3 @Component 更近一步
把applicationcontext.xml 中的除了 beans标签外的内容全部去掉
只需要一句
<context:component-scan base-package= "com. 包到 类名" />
然后在类的上面 @Component(" name ") 你想给类起的名字
就可以直接在实例中context.getBean(“name”) 调用,不过之前在bean中给设置的值没了哦,得在定义类中重新设置。
@Component(“p”)
public class Product {
private int id;
private String name="product 1";
@Autowired
private Category category;
@Component("c")
public class Category {

本文详细介绍了如何使用Spring框架进行配置,包括在src目录下创建applicationcontext.xml文件进行bean的配置,以及如何通过Test.java文件进行测试。此外,还深入探讨了使用@Autowired、@Resource和@Component注解简化配置的方法,使读者能够更加高效地理解和应用Spring框架。

1597

被折叠的 条评论
为什么被折叠?



