什么是 Spring 框架
Spring 框架的理念包括 IoC(Inversion of Control,控制反转)和 AOP(Aspect Oriented Programming,面向切面编程)。
理念:每个 bean 与 bean 之间的关系统一交给 Spring IOC 容器管理。
注解形式启动 Spring
// @Configuration 等于 spring.xml
// 该类也会被注册为 bean,beanId 为小写开头的类名
@Configuration
public class MySpringConfiguration {
// beanId 为方法名称
@Bean
public UserEntity userEntity() {
return new UserEntity("21", "pjw");
}
}
public class MainClass {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MySpringConfiguration.class);
UserEntity userEntity = applicationContext.getBean("userEntity", UserEntity.class);
}
}
@ComponentScan 使用方法
// 指定包里带有 @Component 注解的类注册为 bean,beanId 为小写开头的类名,该类需要有无参构造器
@ComponentScan("com.example.demo.vo")
@Configuration
public class MySpringConfiguration {
}
public class MainClass {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MySpringConfiguration.class);
UserEntity userEntity = applicationContext.getBean("userEntity", UserEntity.class);
}
}