spring boot 的ioc
一、简介
ioc与aop是spring boot的两个核心理念,spring boot是基于注解开发的Spring IOC。
IOC容器一般具备两个基本功能:
1、通过描述管理Bean,包括发布和获取。
2、描述Bean之间的依赖关系
在此有必要解释下什么是bean,bean的中文意思是“豆子”。所谓bean就是可以被重复使用的组件,外界不了解其内部组成与运行方式,外界只能通过其提供的接口来操作。一次编写、任何地方执行、任何地方重用!
bean的特点:
必须具有无参数的构造器,所有的属性都是private的,通过提供setter和getter方法来实现对成员属性的访问
更加详细关于bean的解释可以上百度百科或维基百科去查找:https://baike.baidu.com/item/javaBean
IoC容器是一个管理Bean的容器。在Spring的定义在中,它要求所有的IoC容器都需要实现BeanFactory
接口,它是一个顶级容器接口。
由于BeanFactory的功能不够强大,因此Spring在BeanFactory的基础上,设计了一个更为高级的接口ApplicationContext,它是BeanFactory的子接口之一,在Spring的体系中,BeanFactory和ApplicationContext是最为重要的接口设计,在现实中我们使用的大部分Spring IoC容器是ApplicationContext接口的实现类。
二、如何使用?
1.bean对象的注入:
(1)先创建一个People类:
package com.liwai.study.bean;
/**
* @author syp
*/
public class People {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
(2)然后定义一个配置文件AppConfig:
package com.liwai.study.bean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author syp
*/
@Configuration
public class AppConfig {
@Bean(name = "people")
public People intPeople() {
People people = new People();
people.setName("syp");
people.setAge(18);
return people;
}
}
该处需要理解两个注解:@Configuration、@Bean
@Configuration:可理解为用spring的时候xml里面的标签,代表这是一个Java配置文件,Spring会根据它来生成IoC容器去装配Bean
@Bean:代表将intPeople方法返回的实例对象添加到IoC容器中,而其属性name定义这个Bean的名称,如果没有配置它,则将方法名intPeople作为Bean的名称保存到IoC容器中。
(3)类的@SpringBootApplication
和SpringApplication
的run()
方法,会自动装配Bean到ioc容器中
package com.liwai.study;
import com.liwai.study.bean.People;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
/**
* @author syp
*/
@SpringBootApplication
public class DemoApplication {
private static Logger log = LoggerFactory.getLogger(DemoApplication.class);
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);
People people = ctx.getBean(People.class);
log.info("测试:{}", people.toString());
}
}
输出:测试:People{name=‘syp’, age=18}
更多内容请关注微信公众号“外里科技”