Spring Boot为什么能做到零配置

为何Spring Boot能做到零xml配置
主要是使用了spring3之后提供的注解,来代替xml文件的配置,最核心的是以下两个注解
@Configuration,标注在类上,相当于定义一个配置类,一份spring的配置文件
@Bean,类似于spring配置文件中的<bean id="" class="" />
通过这两个注解就可以用java代码的方式来完成相关spring配置

Demo:
首先导入spring相关包

<properties>
		<spring.version>4.3.7.RELEASE</spring.version>
	</properties>

	<dependencies>
		<!-- spring依赖包 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
	</dependencies>

再定义一个假设是我们需要的类HelloService

package cn.xc.configDemo;


public class HelloService {

	public void sayHello(){
		System.out.println("Hello springConfig...");
	}
	
}

非常平平无奇的一个类,接着再定义一个spring“配置文件类”,使用上面的两个注解

package cn.xc.configDemo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration //相当于定义了一个spring.xml配置文件
public class ApplicationConfigration {

	@Bean //相当于在配置文件中配置了一个bean
	public HelloService helloService(){
		return new HelloService();
	}
	
}

这样一个基本的spring框架就搭好了,接下来测试一下

package cn.xc.configDemo;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class testConfig {

	public static void main(String[] args) {
		
		//获取spring容器,没有配置文件,所以不能用ClassPathXmlApplicationContext
		//传入配置类对象
		AnnotationConfigApplicationContext application = new AnnotationConfigApplicationContext(HelloService.class);
		
		HelloService helloService = application.getBean(HelloService.class);
		
		helloService.sayHello();
	}
	
}

结果:

十二月 04, 2018 8:43:00 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1c49094: startup date [Tue Dec 04 20:42:59 CST 2018]; root of context hierarchy
Hello springConfig...

输出无误

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值