spring学习笔记 星球日one - xml方式配置bean
ide: idea
lib包的导入:http://webcache.googleusercontent.com/search?q=cache:http://zyjustin9.iteye.com/blog/2172445
applicationContext.xml 文件:
如果是java project项目,那么要放在src目录下,同时,需要用 <aop: 来导入p
idea会自动检测此文件,根据上方提示加入spring配置即可
xml 方式 配置 bean:
<?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/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="category" class="com.how2java.pojo.Category" aop:id="10" aop:name="kinome"></bean> <!-- Product 注入 Category对象 --> <bean id="product" class="com.how2java.pojo.Product" aop:name="kinome_product" aop:category-ref="category"></bean> </beans>
package com.how2java.pojo.test; import com.how2java.pojo.Category; import com.how2java.pojo.Product; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestSpring { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); // Category category = ctx.getBean(Category.class); // Category category = (Category) ctx.getBean("category"); // System.out.println(category.getId()+" "+category.getName()); Product product = (Product) ctx.getBean("product"); System.out.println(product.getName()+" "+product.getCategory().getId()+" "+product.getCategory().getName()); } }
package com.how2java.pojo; public class Product { private int id; private String name; private Category category; 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 Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }
package com.how2java.pojo; public class Category { private int id; private String 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; } }