首先需要确定哪些类应该定义为 Bean。对于需要在应用程序中注入的依赖项,需要将其定义为 Bean。例如,在 Spring 应用程序中,可以使用 @Component、@Service 或 @Repository 注释将类定义为 Bean。然后,将这些 Bean 添加到应用程序上下文中,使它们能够被其他对象所引用。例如:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
// ...
}
@Repository
public class UserRepositoryImpl implements UserRepository {
// ...
}
@Configuration
@ComponentScan("com.example")
public class AppConfig {
// ...
}
在这个例子中,UserService 和 UserRepository 都被定义为 Bean,使用了 @Service 和 @Repository 注释。然后,这些 Bean 被添加到应用程序上下文中,通过 @ComponentScan 注释指定要扫描的包名。