Spring中的@Scope和@component註解

默認是單例模式,即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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章