spring autowired

一直有这样一个规则:所有在spring中注入的bean都建议定义成私有的域变量。

 

package com.cuihs;     
    
public class Boss {     
    private Car car;     
    private Office office;     
    
    // 省略 get/setter     
    
    @Override    
    public String toString() {     
        return "car:" + car + "/n" + "office:" + office;     
    }     
}

 

 

 

 

 

下面是使用传统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      
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">     
    <bean id="boss" class="com.cuihs.Boss">     
        <property name="car" ref="car"/>     
        <property name="office" ref="office" />     
    </bean>     
    <bean id="office" class="com.cuihs.Office">     
        <property name="officeNo" value="002"/>     
    </bean>     
    <bean id="car" class="com.cuihs.Car" scope="singleton">     
        <property name="brand" value=" 红旗 CA72"/>     
        <property name="price" value="2000"/>     
    </bean>     
</beans> 


测试代码:

 

 

import org.springframework.context.ApplicationContext;     
import org.springframework.context.support.ClassPathXmlApplicationContext;     
public class AnnoIoCTest {     
    
    public static void main(String[] args) {     
        String[] locations = {"beans.xml"};     
        ApplicationContext ctx =      
            new ClassPathXmlApplicationContext(locations);     
        Boss boss = (Boss) ctx.getBean("boss");     
        System.out.println(boss);     
    }     
}

 

 

@Autowired

Spring 2.5引入了@Autowired注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。

 

package com.cuihs;     
import org.springframework.beans.factory.annotation.Autowired;     
    
public class Boss {     
    
    @Autowired    
    private Car car;     
    
    @Autowired    
    private Office office;     
    
    …     
}

 

<?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-2.5.xsd">     
    
    <!-- 该 BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入 -->     
    <bean class="org.springframework.beans.factory.annotation.     
        AutowiredAnnotationBeanPostProcessor"/>     
    
    <!-- 移除 boss Bean 的属性注入配置的信息 -->     
    <bean id="boss" class="com.cuihs.Boss"/>     
      
    <bean id="office" class="com.cuihs.Office">     
        <property name="officeNo" value="001"/>     
    </bean>     
    <bean id="car" class="com.cuihs.Car" scope="singleton">     
        <property name="brand" value=" 红旗 CA72"/>     
        <property name="price" value="2000"/>     
    </bean>     
</beans>


这样,当Spring窗口启动时,AutowiredAnnotationBeanPostProcessor将扫描Spring容器中所有Bean,当发现Bean中拥有@Autowired注释时就找到和其匹配(默认按类型匹配)的Bean,并注入到对应的地方中去。

 

当然,也可以通过@Autowired对方法或构造函数进行标注,如果构造函数有两个入参,分别是bean1和bean2,@Autowired将分别寻找和它们类型匹配的Bean,将它们作为入参来创建。

 

最后欢迎大家访问我的个人网站:1024s

 

### 如何在Spring框架中刷新或重新加载@Autowired注解的依赖 在Spring框架中,`@Autowired` 注解用于自动装配依赖项,在应用程序上下文初始化期间完。然而,有时可能需要动态地刷新或重新注入这些依赖关系。以下是几种常见的方式: #### 使用 `ApplicationContextAware` 通过实现 `ApplicationContextAware` 接口并调用 `refresh()` 或者获取新的 Bean 实例来更新依赖。 ```java import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class MyService implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } public void refreshDependency() { // 获取最新的Bean实例 MyComponent myComponent = (MyComponent) context.getBean("myComponent"); // 更新员变量或其他逻辑... } } ``` 这种方法适用于希望在整个应用范围内访问和管理Beans的情况[^1]。 #### 利用 `@RefreshScope` 和 Spring Cloud Config 对于基于微服务架构的应用程序来说,推荐使用带有 `@RefreshScope` 的组件。此特性允许在不重启整个应用程序的情况下重载配置属性以及相应的依赖注入。 ```yaml management: endpoints: web: exposure: include: "refresh" ``` ```java @RestController @RequestMapping("/api/refresh") @RefreshScope public class RefreshController { @Autowired private MyComponent myComponent; @GetMapping public ResponseEntity<String> triggerRefresh(){ // 这里可以触发某些业务操作 return ResponseEntity.ok("Dependencies refreshed."); } } ``` 当 `/actuator/refresh` 终端被调用时,所有标记了 `@RefreshScope` 的beans都会得到最新版本的依赖注入[^2]。 #### 手动销毁并重建目标Bean 另一种方法是在运行时手动移除旧版bean定义再创建新版bean定义,但这通常不是最佳实践因为涉及到复杂的生命周期管理和潜在的风险。 ```java @Autowired private AutowireCapableBeanFactory beanFactory; // 销毁当前bean context.destroySingletons(); // 创建新bean Object newBeanInstance = beanFactory.createBean(MyClass.class); ``` 这种方式应当谨慎考虑其适用场景及其带来的副作用[^3]。 #### 注意事项 - 动态刷新依赖应仅限于必要的场合,过度频繁的操作可能会引发性能问题。 - 对于大多数情况而言,默认的一次性静态注入已经足够满足需求。 - 如果确实存在复杂多变的需求,则建议评估是否可以通过其他设计模式(如工厂模式)更好地解决问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值