[java][spring]test1:AOI/DI

step1:

在package:pojo下建立Category类,用来作为操作对象:

代码:

package com.how2java.pojo;
 
public class Category {
 
    private int id;	//定义变量id;
    private String name;//定义变量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; } //定义setter和getter;}
 step2: 

建立Spring核心配置文件applicationContext:代码:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"<!--xml name space/xml命名空间;初始化bean的格式文档地址-->
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<!-- xml所遵守的标签规范;辅助初始化bean-->
xmlns:aop="http://www.springframework.org/schema/aop"
<!-- 辅助建立aop/面向切面编程--> 
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
 <!-- Spring上下文,包括资源加载文件--> 
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 name="c" class="com.how2java.pojo.Category"> <property name="name" value="category 1" /> </bean> <!-- 初始化category类,关键字为"c",变量"name"注入属性"caterogy 1"--></beans>
 step3: 

实际获取对象:

package com.how2java.test;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.how2java.pojo.Category;
 
public class TestSpring {
 
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                new String[] { "applicationContext.xml" });
 //加载配置文件;
        Category c = (Category) context.getBean("c");
 //获取对象c:Category;        
        System.out.println(c.getName());
    }
}

step4:通过ref 注入对象:

    <bean name="p" class="com.how2java.pojo.Product">创建对象p:product;
        <property name="name" value="product1" />属性name注入product 1;
        <property name="category" ref="c" /> 属性category注入对象Category;
    </bean>




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值