srping 用bean id和@Bean注解注入

1、springdemo\src\main\resources\beans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="person" class="com.it.Person">
        <property name="name" value="tom"></property>
        <property name="age" value="23"></property>
    </bean>
</beans>

2、springdemo\src\main\java\com\it\config\PersonConfig.java  配置类

import com.it.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class PersonConfig {
    @Bean
    public Person person() {
        return new Person("刘正", 31);
    }
}

3、springdemo\src\main\java\com\it\Person.java 实体类

public class Person {
    private String name;
    private int age;
    public Person() {}
    public Person(String name, int age){
        this.name = name;
        this.age = 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;
    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

4、springdemo\src\main\java\com\it\PersonTest.java 测试类

import com.it.config.PersonConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PersonTest {
    public static void main(String [] args) {
        ApplicationContext applicationContext1 = new ClassPathXmlApplicationContext("beans.xml");
        Person person1 = (Person)applicationContext1.getBean("person");
        System.out.println(person1);

        ApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(PersonConfig.class);
        Person person2 = (Person)applicationContext2.getBean("person");
        System.out.println(person2);
    }
}
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读