@Import注解的作用是把类加入Spring IOC容器。
有多种方式能让类加IOC容器管理,如@Bean、@Component等,@Import是另外一种方式,更加快捷。
1. 定义普通类
package com.demo;
public class TestA {
private Integer id = 1;
private String name = "TestA";
public void print(){
System.out.println(this.toString());
}
}
2. 定义配置类,并引入普通类
package com.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Import({TestA.class})
@Configuration
public class ImportConfig {
}
另外一种写法是不需要配置类,直接在启动类中引入需要注入spring容器的类。
package com.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
@SpringBootApplication
@Import({TestA.class})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3. 定义测试类
package com.demo.controller;
import com.demo.TestA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/importtest")
public class DemoController {
@Autowired
private TestA testA;
@RequestMapping("/test1")
public String test() {
testA.print();
return "";
}
}
4. 启动springboot启动程序
package com.demo;
import com.demo.util.SpringUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
5. 启动应用程序,执行测试,可以看到testA已经被自动注入了。