美文网首页程序员我爱编程
踩坑之Bean自动初始化

踩坑之Bean自动初始化

作者: 06d589e5c6d8 | 来源:发表于2018-04-13 12:04 被阅读0次

代码:

/* * Copyright 2012-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */

package yjnic;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Test {
    @Bean
    String home() {
        System.out.println("this will be print out without use it!");
        return "Hello World!!!!";
    }
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Test.class, args);
    }
}

一开始以为没有使用 home 这个 bean 不是初始化 ,结果我错了,
结果

一大坨输出blabla......
this will be print out without use it!
一大坨输出blabla.......

然后看了下相关资料,大概猜测了下(哪位路过的大侠看到有错,麻烦留言下,避免我坑到后来者!!)
spring boot 会将扫描到的 bean (@Scope("prototype") 除外)new 一下,然后用一个容器保存起来,用的时候直接到这个容器去拿

如果加上@Scope("prototype")

package yjnic;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;


@SpringBootApplication
public class Test {


    @Bean
    @Scope("prototype") // 加了这个
    String home() {
        System.out.println("this will be print out without use it!");
        return "Hello World!!!!";
    }

    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext ctx = SpringApplication.run(Test.class, args);
        System.out.println("begin use the bean");
        ctx.getBean("home");// 获取他
    }

}

结果

一大坨输出blabla......
begin use the bean
this will be print out without use it!

这个会相对来说比较好理解,
加上 @Scope("prototype") 是为了让作用域改成 每次获取 的都是一个新实例,spring 就没必要一开始就 new 一个出来,所以会在使用的时候才 new 一个实例出来

相关文章

网友评论

    本文标题:踩坑之Bean自动初始化

    本文链接:https://www.haomeiwen.com/subject/icrckftx.html