Importing Spring configuration file

@ImportResource (convenient)
to import the configuration file, so that the configuration file to take effect
Usage:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class DemoApplication {
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}

However, this method requires a single injection of a single configuration file, considerable trouble, Spring Boot recommended way to add components: full annotation mode

  • First, we have to write a configuration class ======== Spring configuration file
  • Use @Bean add a component to a container
package com.example.demo.config;

import com.example.demo.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/*
* 指明当前类是配置类,替代之前的Spring配置文件
* 在之前的配置文件中<bean></bean>标签来添加组件,而在配置类中用@Bean注解
* */
@Configuration
public class Myconfig {
   //将方法的返回值添加到容器中,容器中组件默认的id就是方法名
   @Bean
   public HelloService helloService(){
       return new HelloService();
   }
}

have a test

//注意ApplicationContext不要导错包
	@Autowired
	ApplicationContext ioc;
	@Test
	void testHelloWord(){
		boolean n=ioc.containsBean("helloService");
		System.out.println(n);
	}

result:
Here Insert Picture Description

Published 73 original articles · won praise 20 · views 4455

Guess you like

Origin blog.csdn.net/lzl980111/article/details/103779668