1Spring容器
(1)容器的定义:生产实例的工厂,管理容器中的bean.
(2)bean的定义:bean是Spring管理的基本对象,所有的组件都能都当成bean进行管理。Spring容器负责管理bean的生命周期,创建bean、装配bean、销毁bean。
(3)spring核心接口:BeanFactory和ApplicationContext。BeanFactory:负责配置、创建、管理Bean。ApplicationContext是BeanFactory的一个接口,因此称之为上下文,spring容器负责管理Bean与Bean之间的依赖关系。
(4)DI:依赖注入,主要是通过外部的方式实现注入的。能够实现对象之间的解耦。
(5)IOC:控制反转,将bean注入到其他的类中时,关于bean的创建、装配、销毁都交给了Spring容器。
2装配Bean
(1)注入bean的方式(DI):
1)构造器注入。
2)get、set方式注入(属性注入)。
3)接口注入。
(2)装配Bean的方式:
1)XML方式装配Bean。
2) java中显示配置。
3)隐式的bean发现机制和自动装配。
(3)装配bean
1)组件扫描(component scanning):Spring会发现应用上下文所创建的bean。
2)自动装配(autowiring):Spring自动满足bean之间的装配。
–>在装配Bean的时候,首先在Spring的上下文能够通过某些标识(例如@Component)识别这个类是一个组件,继而,关于这个组件后续的一切交给Spring容器了。Spring容器识别这个组件后,才会将它装配成Bean,创建成Bean,管理Bean的一切。类要做的就是让Spring容器识别它是一个bean,让Spring容器可以识别的注解包括:@Component 、@Repository、@ Controller、@Service 、@Configration一般和@Bean一起使用。
–>Spring要做的就是能够发现在Spring的上下文中组件,然后管理这些组件,将这些组件装配成Bean。Spring识别组件的注解@ComponentScan。
3例子
/**
*声明这个类为组件类,并告知Spring要为他创建bean
*同样声明组件的注解还有:
*/
@Component
public class SgtPeppers {
private String title = "play...SgtPeppers implements CompactDisc";
public void play() {
System.out.println(title);
}
}
@Component注释的类,能够被Spring识别为组件,Spring容器会为这个类生成bean。
测试类
public class TestDemo extends BaseTestCase {
@Autowired
private SgtPeppers sgtPeppers;
@Test
public void test() {
sgtPeppers.play();
}
}
我封装了一下测试类
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { AppleApplication.class })
public abstract class BaseTestCase {
}
在AppleApplication中有扫描整个类的注解。
AppleApplication代码, @SpringBootApplication中包含几个注解,它会扫描所有以”com.demo”开始的包内的注解。
@SpringBootApplication(scanBasePackages = { "com.demo" })
public class AppleApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(getClass());
}
public static void main(String[] args) {
new SpringApplicationBuilder(AppleApplication.class).bannerMode(Banner.Mode.OFF).web(true).run(args);
}
}