spring注入ApplicationContext对象的几种方式

本文详细介绍了在Spring框架中如何使用不同的方式注入ApplicationContext,包括实现接口方式、直接通过Autowired注解注入、构造器注入以及在@Configuration注解的配置类中通过构造函数注入ApplicationContext的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现接口方式:

@Component
public class Shop implements ApplicationContextAware{

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }

    public  void print(){
        System.out.println("*******"+applicationContext.getClass().getName());
    }
}

在@Component、@Configuration、@Service等注解下直接通过Autowired注入:

@Component
public class TestDirect{
 
    @Autowired
    private ApplicationContext applicationContext;
 
    public void print(){
        System.out.println("*********"+applicationContext.getClass().getName());
    }
}

构造器注入:

@Component
public class TestConstructor {
    private ApplicationContext applicationContext;
 
    public TestConstructor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
 
    public  void print(){
        System.out.println("********"+applicationContext.getClass().getName());
    }
}

@Configuration注解所注释的配置类也可通过构造函数注入ApplicationContext

代码:

public interface AA {
    int f();
}

 

public class BB implements AA {
    @Override
    public int f() {
        return 6;
    }
}

 

@Configuration
public class TestBean {

    @Bean
    public Computer computer16(){
        return new Computer("HP");
    }

    @ConditionalOnBean(Cpu.class)
    @Bean
    public BB computer2(Cpu computer){
        System.out.println("----********"+computer);
        return new BB();
    }

}

可以通过构造函数注入ApplicationContext

@Configuration
public class ConfigTestConstr {
    private ApplicationContext applicationContext;

    public ConfigTestConstr(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    public void initConsumer() {
        System.out.println(applicationContext.getBean(BB.class).f());
    }
}

启动类:

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SourcecodeApplication.class);
//        AA aa = context.getBean(BB.class);
//        System.out.println(aa.f());
    }

}

 

 

### Spring框架中配置Bean的不同方法 #### 使用XML配置文件 通过XML配置文件来定义和配置Spring中的bean是最传统的方式之一。开发者可以在`applicationContext.xml`或其他自定义命名的XML文件中声明bean及其依赖关系。 ```xml <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 --> <bean id="exampleBean" class="com.example.ExampleClass"> <!-- 设置构造参数 --> <constructor-arg value="someValue"/> <!-- 或者设置属性 --> <property name="propertyName" value="propertyValue"/> </bean> </beans> ``` 这种方式下,所有的bean定义信息最终都会被转换成`BeanDefinition`的形式存储起来[^1]。 #### 基于Java类的配置方式 随着版本迭代,Spring引入了基于Java类来进行bean配置的支持,这使得代码更加简洁易懂,并且可以充分利用编译期检查的优势。 ```java @Configuration public class AppConfig { @Bean public ExampleClass exampleBean(){ return new ExampleClass(); } } ``` 这种方法不仅能够替代传统的XML配置,还可以更方便地实现复杂的逻辑判断以及动态调整bean的行为。 #### 注解驱动的自动装配机制 为了简化开发流程并提高灵活性,Spring提供了多种注解用于快速完成bean之间的关联工作。比如: - `@Component`: 表明该类是一个组件,可用于扫描路径下的自动注册; - `@Autowired`: 自动注入其他bean实例; - `@Qualifier`: 当存在多个同类型的bean时指定特定的一个进行注入; 这些特性共同构成了强大的DI(Dependency Injection)功能,在不需要显式编写大量配置的情况下实现了高效的对象管理和协作[^2]。 #### 综合应用案例展示 下面给出一段综合运用上述几种技术手段的例子,展示了如何在一个项目内部灵活调配资源和服务。 ```java // Service layer component with autowired repository dependency. @Service public class UserService { private final UserRepository userRepository; @Autowired public UserService(UserRepository userRepository){ this.userRepository = userRepository; } // ... service methods ... } // Repository interface extending CrudRepository for database operations. @Repository interface UserRepository extends CrudRepository<User, Long> {} // Configuration class defining beans programmatically alongside annotated components. @Configuration @ComponentScan(basePackages = "com.example") public class ApplicationConfig { @Bean public DataSource dataSource(){ EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); return builder.setType(EmbeddedDatabaseType.HSQL).build(); } } ``` 这段代码片段说明了即使是在同一个应用程序内也可以混合采用不同风格的bean配置策略,从而达到最佳实践效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值