创建springboot项目。
1.1pom.xml
org.springframework.boot
spring-boot-starter-web
1.2controller控制层
@RestController
public class HeloWorldController {
@RequestMapping("/")
public String getValue(){
return "SpringBoot,Hello World";
}
}
@RestController:复合注解,封装@Controller、@ResponseBody
@RequstMapping:请求路径注解
1.3web展示 2.自定义bean注入ioc容器 方式(1):配置文件application.properties注入 1)bean@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
String brand;
Integer price;
get()、set()、toString();
}
@Component:声明为一个组件
@ConfigurationProperties:扫描配置文件前缀,组件注入容器
2)application.propertiesmycar.brand: BYD mycar.price: 1111113)controller
//@EnableConfigurationProperties(car.class)
@RestController
public class HeloWorldController {
@Autowired
Car car;
@RequestMapping("car")
public Car getcar(){
return car;
}
}
@Autowired:注入容器中的组件
4)web展示结果 5) 扩展@EnableConfigurationProperties注解方式(1)中使用@Component注解就不需要使用@EnableConfigurationProperties,使用@EnableConfigurationProperties则不需使用@Component。并@EnableConfigurationProperties需与@ConfigurationProperties连用,扫描@ConfigurationProperties注解标识的类.class。
原因:当我们引用第三方jar包时,@Component标注的类是无法注入到spring容器中的,这时我们可以用@EnableConfigurationProperties来代替@Component
方式(2):配置文件XML注入 1)beanpublic class User {
public String name;
public Integer age;
get()、set()、toString();
}
2)XML
id:组件名称
class:组件类型
property:bean字段。value:bean字段数值。
3)组件验证@SpringBootApplication
@ImportResource("classpath:beans.xml")//指定导入某一个xml文件,将组件注入ioc容器
public class MainApplication {
public static void main(String[] args) {
//返回ioc容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class,args);
boolean haha = run.containsBean("haha");//导入配置文件后,ioc容器才有haha组件
System.out.println("haha组件:"+haha+");
}
}
@ImportResource:扫描xml文件,注入容器
方式(3):配置类Config注入 1)bean 2)config@Configuration
public class MyConfigBean {
@Bean //给容器添加组件,返回类型就是组件的名字,也就是组件在容器中的实例,组件能被其他组件调用
public User getUser(){
return new User("lisi",20);
}
@Bean("zhangsan") //自定义组件名
public Pet getZhangsan(){
return new User("zhangsan",22);
}
}
@Configuration:能够为容器创建自定义组件,单实例
@Bean("xx"):自定义组件名称
3)测试结果略


