從廈門回來的2024/4/9 晚上23點的bean註解

redzhengtao發表於2024-04-09

Bean註冊

如果要註冊的bean物件來自第三方(不是自定義的),是無法使用@Component及衍生註解宣告bean的
@Bean

安裝jar包到maven本地倉庫指令碼
mvn install:install-file -Dfile=C:\Users\Administrator\Desktop\資料\02_Bean註冊資料\common-pojo-1.0-SNAPSHOT.jar -DgroupId=cn.itcast -DartifactId=common-pojo -Dversion=1.0 -Dpackaging=jar

package com.atguigu.boot3web;

import cn.itcast.pojo.Country;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Boot3WebApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Boot3WebApplication.class, args);
        Country country = context.getBean(Country.class);
        System.out.println(country);
    }


    //注入country物件
    @Bean
    public Country country(){
        return new Country();
    }
}


控制檯輸出

2024-04-09 23:08:05.055 INFO 16668 --- [ main] c.atguigu.boot3web.Boot3WebApplication : Starting Boot3WebApplication using Java 17.0.9 on LAPTOP-F1PA7UHF with PID 16668 (D:\work\shanguigu\boot3-web\target\classes started by 114514 in D:\work\shanguigu\boot3-web)
2024-04-09 23:08:05.057 INFO 16668 --- [ main] c.atguigu.boot3web.Boot3WebApplication : No active profile set, falling back to 1 default profile: "default"
2024-04-09 23:08:05.719 INFO 16668 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2024-04-09 23:08:05.728 INFO 16668 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2024-04-09 23:08:05.728 INFO 16668 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.68]
2024-04-09 23:08:05.813 INFO 16668 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2024-04-09 23:08:05.813 INFO 16668 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 722 ms
2024-04-09 23:08:06.010 INFO 16668 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html]
2024-04-09 23:08:06.081 INFO 16668 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2024-04-09 23:08:06.088 INFO 16668 --- [ main] c.atguigu.boot3web.Boot3WebApplication : Started Boot3WebApplication in 1.318 seconds (JVM running for 1.954)
Country{name='null', system='null'}

Process finished with exit code 130

然後呢,放在啟動類是不建議的

相關文章