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

Java程序员最常见的SpringBoot有那些组件注册方式?
Java程序员最常见的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;br/>@SpringBootApplication
//使用@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.优势:可以指定XML文件,用于以前的项目迁移
2.问题:XML配置冗余复杂,现在都是基于注解和JDKConfig
3.拓展:IDEA中的Beans查看显示图标为

转发+关注后私信我回复【架构资料】即可免费领取全套架构师学习资料

猜你喜欢

转载自blog.51cto.com/14698881/2473980
今日推荐