spring给容器注册组件 的几种方式

环境搭建:
   新建一个maven项目,引入依赖
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.7.RELEASE</version>
    </dependency>

创建一个简单的类Person
package com.yang.spring.domain;

public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person() {
        System.out.println("我被初始化了............");
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

   

1.使用传统的xml进行配置
<bean id="xiaohui" class="com.yang.spring.domain.Person">
    <property name="name" value="yangxiaohui"></property>
    <property name="age" value="20"></property>
</bean>
创建一个测试类
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext ctx  = new ClassPathXmlApplicationContext("beans.xml");
        Person p = (Person) ctx.getBean("xiaohui");
        System.out.println(p);

    }
}

  

猜你喜欢

转载自www.cnblogs.com/yangxiaohui227/p/11941384.html