2026/1/13 6:11:13
网站建设
项目流程
做网站中怎么设置单张图片,国内专业网站建设,php成品网站,工业企业网站建设在Spring Boot中#xff0c;依赖注入是一项核心特性#xff0c;它有助于创建松散耦合的应用程序。
1. 构造函数注入
构造函数注入通过类的构造函数来传递依赖。这确保了在对象创建时#xff0c;依赖就已经准备好#xff0c;并且不可变。如果一个类的依赖在其整个生命周期内…在Spring Boot中依赖注入是一项核心特性它有助于创建松散耦合的应用程序。1. 构造函数注入构造函数注入通过类的构造函数来传递依赖。这确保了在对象创建时依赖就已经准备好并且不可变。如果一个类的依赖在其整个生命周期内都不会改变构造函数注入是一个很好的选择。它还能帮助确保依赖不为空因为构造函数参数通常是必需的。示例代码假设我们有一个UserService依赖于UserRepository。首先定义UserRepository接口和实现类importorg.springframework.stereotype.Repository;RepositorypublicclassUserRepository{publicvoidsaveUser(Stringuser){System.out.println(Saving user: user);}}然后定义UserService通过构造函数注入UserRepositoryimportorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;ServicepublicclassUserService{privatefinalUserRepositoryuserRepository;AutowiredpublicUserService(UserRepositoryuserRepository){this.userRepositoryuserRepository;}publicvoidregisterUser(Stringuser){userRepository.saveUser(user);}}在Spring Boot中Autowired注解并非必需如果构造函数只有一个Spring会自动进行依赖注入。上述代码可以简化为importorg.springframework.stereotype.Service;ServicepublicclassUserService{privatefinalUserRepositoryuserRepository;publicUserService(UserRepositoryuserRepository){this.userRepositoryuserRepository;}publicvoidregisterUser(Stringuser){userRepository.saveUser(user);}}2. Setter方法注入Setter方法注入通过调用Setter方法来设置依赖。这种方式更加灵活因为可以在对象创建后再设置依赖。适用于依赖在对象创建时可能不可用或者依赖可能在对象的生命周期内发生变化的情况。示例代码同样基于前面的UserRepository定义使用Setter注入的UserServiceimportorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;ServicepublicclassUserService{privateUserRepositoryuserRepository;AutowiredpublicvoidsetUserRepository(UserRepositoryuserRepository){this.userRepositoryuserRepository;}publicvoidregisterUser(Stringuser){userRepository.saveUser(user);}}3. 字段注入属性注入字段注入直接在类的字段上使用注解来注入依赖。这种方式代码简洁但不利于单元测试因为难以在测试中替换依赖。示例代码importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;ServicepublicclassUserService{AutowiredprivateUserRepositoryuserRepository;publicvoidregisterUser(Stringuser){userRepository.saveUser(user);}}4. 基于Java配置类的依赖注入在Spring Boot中除了使用组件扫描和自动装配还可以通过Java配置类来手动配置Bean及其依赖关系。这种方式在需要更精细控制Bean的创建和配置时非常有用。示例代码首先创建一个Java配置类AppConfigimportorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;ConfigurationpublicclassAppConfig{BeanpublicUserRepositoryuserRepository(){returnnewUserRepository();}BeanpublicUserServiceuserService(UserRepositoryuserRepository){returnnewUserService(userRepository);}}然后可以在其他组件中使用UserServiceSpring会根据配置类来注入依赖。5. 基于注解驱动的条件注入有时候我们可能希望根据某些条件来决定是否注入某个依赖。Spring Boot提供了基于注解的条件注入方式如Conditional注解及其变体。示例代码假设我们有一个DatabaseConfig类根据系统属性来决定是否创建DataSourceimportorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Conditional;importorg.springframework.context.annotation.Configuration;importjavax.sql.DataSource;importorg.apache.tomcat.jdbc.pool.DataSourceasTomcatDataSource;ConfigurationpublicclassDatabaseConfig{Value(${use.in.memory.database:false})privatebooleanuseInMemoryDatabase;BeanConditional(InMemoryDatabaseCondition.class)publicDataSourceinMemoryDataSource(){TomcatDataSourcedataSourcenewTomcatDataSource();dataSource.setUrl(jdbc:h2:mem:testdb);dataSource.setDriverClassName(org.h2.Driver);dataSource.setUsername(sa);dataSource.setPassword(password);returndataSource;}BeanConditional(ProductionDatabaseCondition.class)publicDataSourceproductionDataSource(){TomcatDataSourcedataSourcenewTomcatDataSource();dataSource.setUrl(jdbc:mysql://localhost:3306/productiondb);dataSource.setDriverClassName(com.mysql.cj.jdbc.Driver);dataSource.setUsername(root);dataSource.setPassword(password);returndataSource;}}这里定义了两个DataSource的BeaninMemoryDataSource和productionDataSource分别基于不同的条件进行创建。Conditional注解的参数是一个实现了Condition接口的类通过实现matches方法来定义条件逻辑。例如importorg.springframework.context.annotation.Condition;importorg.springframework.context.annotation.ConditionContext;importorg.springframework.core.type.AnnotatedTypeMetadata;publicclassInMemoryDatabaseConditionimplementsCondition{Overridepublicbooleanmatches(ConditionContextcontext,AnnotatedTypeMetadatametadata){returncontext.getEnvironment().getProperty(use.in.memory.database,Boolean.class,false);}}importorg.springframework.context.annotation.Condition;importorg.springframework.context.annotation.ConditionContext;importorg.springframework.core.type.AnnotatedTypeMetadata;publicclassProductionDatabaseConditionimplementsCondition{Overridepublicbooleanmatches(ConditionContextcontext,AnnotatedTypeMetadatametadata){return!context.getEnvironment().getProperty(use.in.memory.database,Boolean.class,false);}}