声明Java Bean的方式(告诉Spring管理哪些对象)

172 阅读2分钟

在 Spring Boot 中,声明bean的方式(即被 Spring 管理的组件)可以是以下形式之一,具体取决于它们的角色和定义方式:


1. 通过注解声明的 Bean(自动扫描)

Spring 会自动扫描 @Component@Service@Repository@Controller 等注解的类,并将其实例化为 Bean。

示例:Service 类(@Service 注解)

@Service // 声明Bean - 标记为 Spring 管理的 Bean
public class UserService {

    private final UserRepository userRepository;

    // 构造器注入(推荐)
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
}

示例:Repository 类(@Repository 注解)

@Repository // 声明Bean - 标记为数据访问层的 Bean
public class JdbcUserRepository implements UserRepository {

    private final JdbcTemplate jdbcTemplate;

    public JdbcUserRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public User findById(Long id) {
        String sql = "SELECT * FROM users WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new UserRowMapper(), id);
    }
}

2. 通过 Java 配置类定义的 Bean(@Configuration + @Bean

适用于第三方库组件或需要手动控制 Bean 的创建逻辑。

示例:配置类定义 Bean

@Configuration // 标记为配置类
public class AppConfig {

    @Bean // 声明Bean - 方法返回的对象会被 Spring 管理
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Bean // 声明Bean - 方法返回的对象会被 Spring 管理
    public DataSource dataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
        dataSource.setUsername("root");
        dataSource.setPassword("password");
        return dataSource;
    }
}

3. 通过 XML 配置定义的 Bean(传统方式)

需要配合 @ImportResource 导入 XML 文件。

XML 文件示例(beans.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 手动定义 Bean - 通过Bean标签定义Bean 需要配合@ImportResource-->
    <bean id="myBean" class="com.example.MyBean"/>
    
    <bean id="userService" class="com.example.UserService">
        <constructor-arg ref="userRepository"/>
    </bean>

    <bean id="userRepository" class="com.example.JdbcUserRepository"/>
</beans>

在 Spring Boot 中导入 XML:

@SpringBootApplication
@ImportResource("classpath:beans.xml") // 导入 XML 配置
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

Bean 的关键特征

  1. 生命周期管理:Spring 负责创建、初始化、销毁 Bean。
  2. 依赖注入:通过 @Autowired、构造器、Setter 等方式注入其他 Bean。
  3. 作用域:默认单例(@Scope("prototype") 可定义多例)。

总结

  • 常用方式:注解(如 @Service) + 构造器注入。
  • 复杂场景:使用 @Configuration 类定义 Bean。
  • 遗留系统:XML 配置(逐步迁移到注解)。
  • 最佳实践:保持 Bean 的单一职责,避免过度依赖 XML。