Spring 框架核心特性
- Ioc 容器:开发者只需定义好 Bean 及其依赖关系,Spring 负责创建和组装这些对象
- AOP:面向切面编程(aspect-oriented programming),定义横切关注点,例如事务管理,统一设置更新时间等
- 事务管理:Spring 提供了一致的事务管理接口, 支持声明式(@Transactional) 和编程式事务,开发者可以轻松的进行事务管理
- MVC 框架:Spring MVC 是一个基于 Servlet API 侯建的 Web 框架,采用了模型-视图-控制器(MVC)架构,它支持灵活的 URL 都到页面控制器的映射,以及多种视图技术
Ioc 容器
- 传统的 JavaSE 是通过 new 来主动的创建对象,而 IoC 将对象的创建、依赖关系和生命周期的控制权交给容器统一管理。
- Bean 就是 Spring 容器创建的单例,用的时候只需要注入就行了。
- Spring IOC 容器利用了 Java 的反射机制动态地加载类,创建对象实例及调用对象方法,反射允许在运行时检查类、属性方法等信息。
依赖注入
注入的时候是 spring 根据这个类名,用反射的方式将对应的单例传进来,赋给这个属性。
构造器注入
不可变依赖,首选
如果用 Lombok,可以用@RequiredArgsConstructor 加 final 字段来省略构造器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import org.springframework.stereotype.Service;
@Service public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) { this.userRepository = userRepository; }
public void register(String username) { userRepository.save(username); } }
|
setter 注入
可选依赖,次选
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
@Service public class UserService {
private UserRepository userRepository;
@Autowired public void setUserRepository(UserRepository userRepository) { this.userRepository = userRepository; }
public void register(String username) { if (userRepository != null) { userRepository.save(username); } } }
|
字段注入(不推荐)
不选
1 2 3 4 5 6 7 8 9 10 11 12 13
| import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
@Service public class UserService {
@Autowired private UserRepository userRepository;
public void register(String username) { userRepository.save(username); } }
|
补充:被注入的依赖类(UserRepository)
带 @Repository 注解,会被 Spring 自动扫描为 Bean,默认作用域为 singleton(单例)。
1 2 3 4 5 6 7 8 9
| import org.springframework.stereotype.Repository;
@Repository public class UserRepository {
public void save(String username) { System.out.println("Saving user: " + username); } }
|
常用注解
@Autowired
@Autowired 用于自动注入依赖。
1 2 3 4 5 6 7 8 9 10
| @Component public class UserService {}
@Component public class UserController { @Autowired private UserService userService; }
|
@Component
@Component 用于标记一个类为 Spring 的 Bean,Spring 会自动将其实例化为一个 Bean 并添加到 Bean 容器
@Configuration
@Configuration 用于标记一个类为 Spring 的配置类,配置类可以包含@Bean 注解的方法,用于定义和配置 Bean,作为全局配置
1 2 3 4 5 6 7
| @Configuration public class AppConfig { @Bean public MyBean myBean() { return new MyBean(); } }
|
@Bean
@Bean 用于标记一个方法作为 Spring 的 bean 工厂方法,Spring 会将这个方法的返回值作为一个 Bean,并添加到 Spring 容器中,如果自定义配置,经常要用到这个注解
@Service
@Service 用于标记一个类为服务层的组件,是@Component 注解的一种特殊形式,用于标记服务层的 bean,一般标记在 serviceImpl(实现类)上
@Repository
@Repository 用于标记一个类为数据访问层的组件,也是@Component 注解的一种特殊形式,用于标记数据访问层的 bean
1 2
| @Repository public class UserRepository {}
|
@Controller
@Controller 用于标记一个类作为控制层的组件,也是@Component 注解的一种特殊形式,用于标记控制层的 bean。这是 MVC 架构中的控制器