常见的SpringBoot组件注册方式有几种?

发布时间:2020-05-27 13:46:02 作者:鸽子
来源:亿速云 阅读:319

Java程序员最常见的SpringBoot有那些组件注册方式?
常见的SpringBoot组件注册方式有几种?

很多程序员在开发的过程中都可能会遇到SpringBoot组件注册这个问题,那么SpringBoot到底有那些组件注册方式呢?
今天主要就来和大家分享这个SpringBoot组件注册的几种方式,希望可以帮大家快速解决当下的这个难题。

传统的XML+@ImportResource【案例demo2】
项目包结构
├─java
│  └─com
│      └─example
│          └─demo2
│              │  Demo2Application.java
│              │  
│              └─entity
│                      Stu.java
│                      
└─resources
application.properties
beans.xml
project.text
beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--id用来标识bean,是唯一的,且只有一个;name定义的是bean的alias,可以有多个,并可能与其他的bean重名。-->
<!--如果id和name都没有指定,则用类全名作为name-->
<bean id="stu" class="com.example.demo2.entity.Stu">
</bean>    
</beans>
Demo2Application(启动程序)
package com.example.demo2;
import com.example.demo2.entity.Stu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ImportResource;@SpringBootApplication<br/" rel="nofollow">br/>@SpringBootApplication<br///使用@ImportResource导入xml资源
@ImportResource(locations = "classpath:/beans.xml")
public class Demo2Application {
public static void main(String[] args) {
//使用ConfigurableApplicationContext上下文即可获取Beans
ConfigurableApplicationContext context = SpringApplication.run(Demo2Application.class, args);
Stu stu = context.getBean("stu", Stu.class);
System.out.println(stu.toString());
//context类型为org.springframework.context.annotation.AnnotationConfigApplicationContext
System.out.println(context.getClass().getName());
context.close();
}
}
ClassPathXmlApplicationContext与ConfigurableApplicationContext的关系

推荐阅读:
  1. SpringBoot项目有哪几种启动方式?
  2. 服务注册的方式有几种

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java springboot bo

上一篇:DP转HDMI的解决方案

下一篇:openpstack-Pike对接cephRBD单集群的配置步骤

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》