Spring中的@Scope和@component注解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yaomingyang/article/details/84554368

默认是单例模式,即scope=“singleton”。另外scope还有prototype、request、session、global session作用域。

  • singleton单例模式
    全局有且仅有一个实例。
  • prototype原型模式
    每次获取Bean的时候都会有一个新的实例。
  • request
    request表示针对每次请求都会产生一个新的Bean对象,并且该Bean对象仅在当前Http请求内有效。
  • session
    session作用域表示煤气请求都会产生一个新的Bean对象,并且该Bean仅在当前Http session内有效。
  • global session
    global session作用域类似于标准的HTTP Session作用域,不过它仅仅在基于portlet的web应用中才有意义。Portlet规范定义了全局Session的概念,它被所有构成某个 portlet web应用的各种不同的portlet所共享。在global session作用域中定义的bean被限定于全局portlet Session的生命周期范围内。如果你在web中使用global session作用域来标识bean,那么web会自动当成session类型来使用。

@component注解会把普通的POJO实例化到Spring容器中去,相当于配置文件中的

  • 创建一个Student类:
package com.config.server.endpoint;

import org.springframework.stereotype.Component;

@Component
public class Student {

    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
  • 测试Student类实例
package com.config.server;

import com.config.server.endpoint.People;
import com.config.server.endpoint.Student;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

@EnableConfigServer
@SpringBootApplication
public class ServerApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(ServerApplication.class, args);
       
        Student student = context.getBean("student", Student.class);
        System.out.println(student);

        Student student1 = context.getBean("student", Student.class);
        System.out.println(student1);

    }
}

  • 打印结果:
com.config.server.endpoint.Student@5922d3e9
com.config.server.endpoint.Student@5922d3e9

猜你喜欢

转载自blog.csdn.net/yaomingyang/article/details/84554368