Spring中如何注册bean和获取bean

Spring中如何注册bean和获取bean

Spring5.x发布了,再次复习一下常用的注册和获取bean的方法。

1.基于xml配置注册于获取bean

2.半注解半xml方式

3.基于注解注册与获取bean

常用于获取bean的类:

ClassPathXmlApplicationContext、

FileSystemXmlApplicationContext、

AnnotationConfigApplicationContext

1、基于xml配置

01、项目准备

建立一个Spring项目,在src/java目录下创建pojo包,建立一个User类。

这里的构造方法、getter/setter方法,toString方法在xml配置中并不一定需要,但在基于注解的时候是必须的。

public class User {

    private String name;
    private Integer id;
    private Integer age;
    private String gender;

    public User(String name, Integer id, Integer age, String gender) {
        this.name = name;
        this.id = id;
        this.age = age;
        this.gender = gender;
    }

    public User() {
    }

    public String getName() {
        return name;
    }

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


    public Integer getId() {
        return id;
    }
   
    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getAge() {
        return age;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

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

02、创建xml配置文件

在resourses目录下创建ApplicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="user" class="com.pojo.User">
        <property name="name" value="Jim"/>
        <property name="age" value="19"/>
        <property name="id" value="1000000"/>
        <property name="gender" value="female"/>
    </bean>
    
    <bean id="user2" class="com.pojo.User">
        <constructor-arg index="0" value="Tom"/>
        <constructor-arg name="age" value="18"/>
        <constructor-arg type="java.lang.Integer" value="100000"/>
        <constructor-arg index="3" value="male"/>
    </bean>
</beans>

03、获取bean

使用ClassPathXmlApplicationContext获取bean.

	@Test
	public void test(){
        //使用ClassPathXmlApplicationContext加载xml,默认从classpath下加载
  		ApplicationContext context = new 			            ClassPathXmlApplicationContext("ApplicationContext.xml");
        User user = context.getBean(User.class);
        System.out.println("bean:"+ user);
    }

使用FileSystemXmlApplicationContext获取bean.

	@Test
    public void test2(){
        //使用FileSystemXmlApplicationContext加载xml,可指定文件位置
        ApplicationContext context = new FileSystemXmlApplicationContext("classpath:ApplicationContext.xml");
        User user2 = context.getBean("user2",User.class);
        System.out.println("bean:"+ user2);
    }

2、半注解半xml

这种还是需要配置文件完成部分操作。

01、创建xml配置文件

在resourses下创建Annotation.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="com.pojo"/>

</beans>

02、使用注解注册bean

在User上加入@Component注解,代表加入IOC容器,使用 @Value注解给字段赋值,可以在set方法上,也可以在字段名上。

@Component注解默认id为类名小写,也可以手动更改。

@Component
public class User {

    @Value("Nike")
    private String name;
    private Integer id;
    private Integer age;
    private String gender;
    
    @Value("19002")
    public void setId(Integer id) {
        this.id = id;
    }

    
}

03、获取bean

此时还有配置文件,所以还是从文件中获取.

 @Test
    public void test3(){
        //使用FileSystemXmlApplicationContext加载xml,可指定文件位置
        ApplicationContext context = new FileSystemXmlApplicationContext("classpath:Annotation.xml");
        User user = context.getBean("user",User.class);
        System.out.println("bean:"+ user);
    }

3、基于注解

从Spring4开始,这种基于注解的开发被广泛使用。

01、配置类

建立com.config包,在包下建立AppConfig.java。

在pojo包下建立Actor.java。

使用@Configuration表明这是一个配置类,配置类具有xml文件具有的所有功能。

@ComponentScan注解可以扫描包。

@Bean注解代表这是一个bean,返回类型即bean类型。

@Import注解可以把其他类注入当前配置中。

@Configuration
@Import({com.pojo.Actor.class})
@ComponentScan(basePackages = "com.pojo")
public class AppConfig {

   	@Bean
    public User user2(){
        return new User("Sally",190002,29,"female");
    }
}
@Component
public class Actor {
    @Value("Dave")
    private String name;

    public String getName() {
        return name;
    }

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

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

02、获取bean

此时使用使用AnnotationConfigApplicationContext获取配置类。

 @Test
    public void test4(){
        //使用AnnotationConfigApplicationContext获取配置类
        //ApplicationContext context = new AnnotationConfigApplicationContext("com.config");
   
        ApplicationContext context = new AnnotationConfigApplicationContext(com.config.AppConfig.class);
        User user = context.getBean("user",User.class);
        System.out.println("bean:"+ user);

    }
    
    
    @Test
    public void test5(){
        //使用AnnotationConfigApplicationContext获取配置类
      
        ApplicationContext context = new AnnotationConfigApplicationContext(com.config.AppConfig.class);

        Actor actor=context.getBean("actor", Actor.class);
        System.out.println(actor);

    }
posted @ 2020-01-06 18:04  cgl_dong  阅读(1813)  评论(0编辑  收藏  举报