Spring框架基础详解
什么是Spring
Spring是一个轻量级的企业级应用开发框架,核心特性是IoC(控制反转)和AOP(面向切面编程)。
Spring项目结构
src/main/java
com.example.demo
controller/
service/
repository/
config/
model/
src/main/resources
application.properties
beans.xml
IoC容器基础
XML配置方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userService" class="com.example.service.UserService">
<property name="userRepository" ref="userRepository"/>
</bean>
<bean id="userRepository" class="com.example.repository.UserRepository"/>
</beans>
Java配置方式
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public UserRepository userRepository() {
return new UserRepository();
}
@Bean
public UserService userService() {
return new UserService(userRepository());
}
}
依赖注入
构造函数注入
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User findById(Long id) {
return userRepository.findById(id);
}
}
Setter注入
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private UserService userService;
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
}
字段注入
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public Product findByName(String name) {
return productRepository.findByName(name);
}
}
Bean作用域
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class BeanScopeConfig {
@Bean
@Scope("singleton")
public SingletonBean singletonBean() {
return new SingletonBean();
}
@Bean
@Scope("prototype")
public PrototypeBean prototypeBean() {
return new PrototypeBean();
}
}
Bean生命周期
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Component
public class LifecycleBean implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Bean初始化完成");
}
@Override
public void destroy() throws Exception {
System.out.println("Bean销毁");
}
}
使用ApplicationContext
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);
System.out.println("获取UserService: " + userService);
String[] beanNames = context.getBeanDefinitionNames();
System.out.println("所有Bean:");
for (String name : beanNames) {
System.out.println(" - " + name);
}
context.close();
}
}
@Component注解
import org.springframework.stereotype.Component;
@Component("myComponent")
public class MyComponent {
public void doSomething() {
System.out.println("Component执行操作");
}
}
import org.springframework.stereotype.Repository;
@Repository
public class UserRepository {
public User findById(Long id) {
return new User(id, "张三");
}
}
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
import org.springframework.stereotype.Controller;
@Controller
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
}
配置属性
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:app.properties")
public class PropertyConfig {
@Value("${app.name}")
private String appName;
@Value("${app.version:1.0}")
private String appVersion;
public String getAppName() {
return appName;
}
public String getAppVersion() {
return appVersion;
}
}
Spring最佳实践
- 优先使用构造函数注入
- 使用@Autowired进行自动装配
- 合理使用Bean作用域
- 利用@Configuration进行Java配置
- 使用@Profile区分环境配置
总结
Spring框架通过IoC容器和依赖注入简化了Java企业级应用开发。掌握Spring的核心概念,是学习其他Spring技术的基础。