Spring小白到菜鸟修炼之基本概念(1)

直接上代码

package first;


/**
 * Spring对bean没有任何要求,只要是一个Java类就行
 */
public class Axe {

    public String chop() {
        return "我是Axe的 chop方法";
    }

}
package first;

/**
 * A对象需要调用B对象,称为依赖
 */

public class Person {

    private Axe axe;

    public void setAxe(Axe axe) {
        this.axe = axe;
    }

    public void useAxe() {
        System.out.println("=========");
        System.out.println("Person->" + axe.chop());

    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="    
          http://www.springframework.org/schema/beans    
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <!-- 使用<bean>来配置Bean,Spring默认调用Bean类的无参构造函数来创建实例,并
           将该实例作为容器中的Bean使用-->
    <bean class="first.Person" id="person">
    <!-- 
         <property>驱动Spring底层调用指定属性的setter方法,
           ref(或者value)是传入setter方法的参数

           控制调用setAxe()方法,将容器中的名为axe Bean作为传入参数
            -->
        <property name="axe" ref="axe" />
    </bean>
    <bean class="first.Axe" id="axe" />
    <bean id="win" class="javax.swing.JFrame" />
    <bean id="dtae" class="java.util.Date" />


</beans>
package first;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Spring核心容器理论
 * 
 * Spring核心容器是一个超级大工厂,所有的对象都会被当成Spring核心容器管理的对象(Bean) Spring管理Bean可以使用xml或者注解实现
 * 
 * 使用xml文件管理bean (1) Spring对xml文件名没有要求
 * 
 */

public class TestDemo {

    public static void main(String[] args) {
/**
 * ApplicationContext是Spring容器的入口
 *   它有两个子类
 *      ClassPathXmlApplicationContext 从类加载路径下搜索配置文件,根据配置文件来创建Spring容器
 *      FileSystemXmlAppicationContext 从文件系统的相对/绝对的路径搜索配置文件,根据配置文件来创建Spring容器
 * 
 *    Spring容器获取Bean对象有两种方法
 *      1 Object getBean(String id) 根据id获取指定bean,需要强制类型转换
 *      2 T   getBean(String name , Class<T> requiredType) 不需要强制类型转换
 *      
 *    获取Bean之后,我们可以像使用普通Java对象一样使用Bean
 */

        ApplicationContext context = new ClassPathXmlApplicationContext(
                "first.xml");
        // 获取id为person的Bean
        Person p = context.getBean("person", Person.class);
        p.useAxe();

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值