spring 怎么获取bean

spring 怎么获取bean,第1张

Spring在代码中获取bean的几种方式

方法一:在初始化时保存ApplicationContext对象

方法二:通过Spring提供的utils类获取ApplicationContext对象

方法三:继承自抽象类ApplicationObjectSupport

方法四:继承自抽象类WebApplicationObjectSupport

方法五:实现接口ApplicationContextAware

方法六:通过Spring提供的ContextLoader

获取spring中bean的方式总结:

方法一:在初始化时保存ApplicationContext对象

ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContextxml"); acgetBean("userService");//比如:<bean id="userService" class="comcloudserviceimplUserServiceImpl"></bean>

说明:这样的方式适用于采用Spring框架的独立应用程序,须要程序通过配置文件手工初始化Spring的情况。

方法二:通过Spring提供的工具类获取ApplicationContext对象

ApplicationContext ac1 = WebApplicationContextUtilsgetRequiredWebApplicationContext(ServletContext sc); ApplicationContext ac2 = WebApplicationContextUtilsgetWebApplicationContext(ServletContext sc); ac1getBean("beanId"); ac2getBean("beanId");

说明:这样的方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象。然后在通过它获取须要的类实例。上面两个工具方式的差别是,前者在获取失败时抛出异常。后者返回null。

方法三:继承自抽象类ApplicationObjectSupport

说明:抽象类ApplicationObjectSupport提供getApplicationContext()方法。能够方便的获取ApplicationContext。

Spring初始化时。会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

方法四:继承自抽象类WebApplicationObjectSupport

说明:类似上面方法。调用getWebApplicationContext()获取WebApplicationContext

方法五:实现接口ApplicationContextAware

说明:实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。Spring初始化时,会通过该方法将ApplicationContext对象注入。

下面是实现ApplicationContextAware接口方式的代码,前面两种方法类似:

public class SpringContextUtil implements ApplicationContextAware { // Spring应用上下文环境 private static ApplicationContext applicationContext; / 实现ApplicationContextAware接口的回调方法。设置上下文环境 @param applicationContext / public void setApplicationContext(ApplicationContext applicationContext) { SpringContextUtilapplicationContext = applicationContext; } / @return ApplicationContext / public static ApplicationContext getApplicationContext() { return applicationContext; } / 获取对象 @param name @return Object @throws BeansException / public static Object getBean(String name) throws BeansException { return applicationContextgetBean(name); } }

尽管,spring提供的后三种方法能够实如今普通的类中继承或实现对应的类或接口来获取spring 的ApplicationContext对象,可是在使用是一定要注意实现了这些类或接口的普通java类一定要在Spring 的配置文件applicationContextxml文件里进行配置。否则获取的ApplicationContext对象将为null。

方法六:通过Spring提供的ContextLoader

WebApplicationContext wac = ContextLoadergetCurrentWebApplicationContext();wacgetBean(beanID);

最后提供一种不依赖于servlet,不须要注入的方式。可是须要注意一点,在server启动时。Spring容器初始化时,不能通过下面方法获取Spring 容器,细节能够查看spring源代码orgspringframeworkwebcontextContextLoader。

总共有6种方法可以实现:

方法一:在初始化时保存ApplicationContext对象 

方法二:通过Spring提供的utils类获取ApplicationContext对象 

方法三:继承自抽象类ApplicationObjectSupport 

方法四:继承自抽象类WebApplicationObjectSupport 

方法五:通过Spring提供的ContextLoader

获取spring中bean的方式总结: 

方法一:在初始化时保存ApplicationContext对象

ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContextxml"); acgetBean("userService");//比如:<bean id="userService" class="comcloudserviceimplUserServiceImpl"></bean>

说明:这样的方式适用于采用Spring框架的独立应用程序,须要程序通过配置文件手工初始化Spring的情况。

方法二:通过Spring提供的工具类获取ApplicationContext对象

ApplicationContext ac1 = WebApplicationContextUtilsgetRequiredWebApplicationContext(ServletContext sc); ApplicationContext ac2 = WebApplicationContextUtilsgetWebApplicationContext(ServletContext sc); ac1getBean("beanId"); ac2getBean("beanId");  

说明:这样的方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象。然后在通过它获取须要的类实例。上面两个工具方式的差别是,前者在获取失败时抛出异常。后者返回null。

方法三:继承自抽象类ApplicationObjectSupport

说明:抽象类ApplicationObjectSupport提供getApplicationContext()方法。能够方便的获取ApplicationContext。

Spring初始化时。会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

方法四:继承自抽象类WebApplicationObjectSupport

说明:类似上面方法。调用getWebApplicationContext()获取WebApplicationContext

方法五:通过Spring提供的ContextLoader

WebApplicationContext wac = ContextLoadergetCurrentWebApplicationContext();wacgetBean(beanID);

API网关的请求转发等内容实际上是通过Ribben来实现的。

Spring Cloud 实现负载均衡通过在RestTemplates  增加@LoadBalanced注解,将Rest请求交给Ribben去管理。

Spring Cloud实现负载主要是用过管理Rest请求来实现,故项目中必须都使用Rest分格的请求

Ribben的配置类LoadBalanceAutoConfiguration主要实现的功能:

    1创建了一个LoadBalanceInterceptor的Bean,用于实现对客户端发起的请求就行拦,是实现客户端的负载均衡。

    2创建了一个LoadBalanceCustomizer的Bean  用于给RestTemplate增加LoadBalanceInterceptor拦截器。

    3维护了一个被@LoadBalance注释的RestTemplate的对象列表,并在这里进行初始化,通过调用LoadBalanceCustomizer的实例来给需要客户端负载均衡的TestTemplate增加LoadBalanceInterceptor拦截器。

    4、LoadBalanceInterceptor拦截去会根据传入的ServiceID去获取具体的实例,拦截去实现的各个方法,

    addServices :向负载均衡器维护的列表中添加服务实例,添加服务的时候会将新加入的实例和之前的所有实例加入List中

    chooseServices:通过Rule(线性轮训、按权重负载、按流量负载)和 Ping来选择具体的服务实例启动的ping的定时任务默10秒

    markServiecsDowe:标示异常的服务实例

    getReachableService:获取当前正常的服务实例

    getAllServices:获取所有维护的服务实例

    5Ribben 的服务实例由Eureka的服务发现来获取,Ribben会将Eureka中注册章的服务转换成自己的服务实例信息。(请求了Eureka的获取服务列表)

    6Ribben 的服务更新器主要通过DynamicServiceListLoadBalancer 来实现

    7Ribben实服务实例和真实地址之间转换的原理,从Netfix的service中获取host和port 如果service中的host和port中的地址和真实地中中的一直则直接返回真实地址,如果不一致则使用service中的host和port结合真实地址中的相关参数,拼接成新的地址。

在choose的时候 使用一个所有服务列表(allList)数中取随机数去可用服务(upList)中取可用的服务,如果取到的服务不可用或者无此服务,线程让步(Threadyield())进行线程让我重新获取新的服务。

线性轮训和RandomRule相似,存了循环条件以外增加了10次的轮训限制,如果10次没有获取到可用的服务,则返回 No available alive serivces after 10 tries  from load balancer

RetryRule增加了一个重试机制,此机制默认使用 RoundRobinRule规则来获取服务,通知定义了一个重试时间(maxRetryMillis),如果在重试时间内没有获取到可用的服务,则重复进行获取,如果超出重试时间还未获取到则返回null

该策略主要是对RoundRobinRule规则的扩展,根据实例的运行情况计算权重,并根据权重来选择实例,以达到最优的分配效果

主要实现有3个

1、定时任务计算权重,初始化的时候启动一个30秒的定时任务来计算服务的权重

2、权重计算    权重计算先获取所有实例服务的平均响应时间获取平均响应时间的总和,然后逐个计算每个实例的权重(WeigthSoFar+totalResponseTime-实例的平均响应时间)

3、选择实例  判断最小权重是否大于0001 如果小于0001则使用线性轮训的策略,否则 生成一个[0,最大权重值]的随机数,选择一个区间内的随机数,选择随机数所在区间内的服务。

内部使用RoundRobinRule规则来实现策略,但是经常继承这个类来实现高级策略的制定

继承了CIientConfigEnableRoundRobinRule规则,在实现时注入了负载均衡器的统计对象LoadBalacneStats ,同时在选择实例的时候利用LoadBalaceStats来统计信息来来选择满足要求的实例

如果第一次请求LoadBalacneStats 为null,会使用线性轮训的方式来获取满足要求的实例,之后每选择都会统计LoadBalacneStats ,之后选择的时候会选择请求最少的服务。

基于委托的方式来过滤清单的一种策略,在选择服务的时候先将获取到的服务清单通过Predicate配置的过滤条件来过滤一部分服务,然后再通过线性轮训的方式来进行服务选择。实现过滤使用的comgooglecommombasepridicate中的apply来实现的,new Predicate(loadBalanceKey,service),关于服务的统计信息和负载均衡器的选择算法传递股过来的key来过滤、

Ribben注入的时候会进行一些自动化的配置,自动构建一下接口来提供使用

IClientConfig  来配置Ribben客户端的简单配置

IPing  来实现Ribben的实例检查策略

IRule 来实现负载均衡的策略  默认采用区域感知

ServiceList ;实现服务清单的维护机制

ServivcerFilterList 来实现服务过滤规则  默认采用区域感知

ILoadBalance 负载均衡区 默认采用区域感知

可以在创建Ribben的时候创建一个Configuration来定义以上的接口来覆盖默认的配置。

是的,你说得对。lookup和bean是两种不同的依赖注入方式,它们不能同时使用。

- lookup是一种动态依赖注入方式,它允许在运行时从容器中获取一个对象的实例。这种方式适用于需要频繁创建对象的场景,例如在Web应用中,每个请求都需要创建一个新的对象实例。

- 而bean则是一种静态依赖注入方式,它在容器启动时就将对象创建好,并将其注入到需要它的类中。这种方式适用于需要保持对象状态的场景,例如数据库连接池、线程池等。

因此,如果使用了lookup方式获取对象实例,就不能使用bean方式进行依赖注入。

两个不同的bean里都引用同一个bean对象

即A B 同时都引用了C,这时候如果想数据共享,那么你要在spring里设置这个C为单例

在spring依赖注入配置里bean的作用域

<bean id="role" class="springchapter2maryGameRole" scope="singleton"/>

默认是单例模式,即scope="singleton"

另外scope还有prototype、request、session、global session作用域

scope="prototype"多例

请采纳哈

方法一:在初始化时保存ApplicationContext对象 方法二:通过Spring提供的utils类获取ApplicationContext对象 方法三:继承自抽象类ApplicationObjectSupport 方法四:继承自抽象类WebApplicationObjectSupport 方法五:实现接口ApplicationContextAware 方法六:通过Spring提供的ContextLoader

获取spring中bean的方式总结:

方法一:在初始化时保存ApplicationContext对象

[html] view plain copy

ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContextxml");

acgetBean("beanId");

说明:这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。

方法二:通过Spring提供的工具类获取ApplicationContext对象

[java] view plain copy

ApplicationContext ac1 = WebApplicationContextUtilsgetRequiredWebApplicationContext(ServletContext sc);

ApplicationContext ac2 = WebApplicationContextUtilsgetWebApplicationContext(ServletContext sc);

ac1getBean("beanId");

ac2getBean("beanId");

说明:这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。

方法三:继承自抽象类ApplicationObjectSupport

说明:抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取ApplicationContext。

Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。

方法四:继承自抽象类WebApplicationObjectSupport

说明:类似上面方法,调用getWebApplicationContext()获取WebApplicationContext

方法五:实现接口ApplicationContextAware

说明:实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。Spring初始化时,会通过该方法将ApplicationContext对象注入。

以下是实现ApplicationContextAware接口方式的代码,前面两种方法类似:

[java] view plain copy

package comifabooMiomOmmgutil;

import orgspringframeworkcontextApplicationContext;

import orgspringframeworkcontextApplicationContextAware;

public class SpringContextUtil implements ApplicationContextAware {

private static ApplicationContext applicationContext;

/

实现ApplicationContextAware接口的context注入函数, 将其存入静态变量

/

public void setApplicationContext(ApplicationContext applicationContext) {

SpringContextUtilapplicationContext = applicationContext; // NOSONAR

}

/

取得存储在静态变量中的ApplicationContext

/

public static ApplicationContext getApplicationContext() {

checkApplicationContext();

return applicationContext;

}

/

从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型

/

@SuppressWarnings("unchecked")

public static <T> T getBean(String name) {

checkApplicationContext();

return (T) applicationContextgetBean(name);

}

/

从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型

/

@SuppressWarnings("unchecked")

public static <T> T getBean(Class<T> clazz) {

checkApplicationContext();

return (T) applicationContextgetBeansOfType(clazz);

}

/

清除applicationContext静态变量

/

public static void cleanApplicationContext() {

applicationContext = null;

}

private static void checkApplicationContext() {

if (applicationContext == null) {

throw new IllegalStateException("applicaitonContext未注入,请在applicationContextxml中定义SpringContextHolder");

}

}

}

虽然,spring提供的后三种方法可以实现在普通的类中继承或实现相应的类或接口来获取spring 的ApplicationContext对象,但是在使用是一定要注意实现了这些类或接口的普通java类一定要在Spring 的配置文件applicationContextxml文件中进行配置。否则获取的ApplicationContext对象将为null。

方法六:通过Spring提供的ContextLoader

[java] view plain copy

WebApplicationContext wac = ContextLoadergetCurrentWebApplicationContext();

wacgetBean(beanID);

最后提供一种不依赖于servlet,不需要注入的方式。但是需要注意一点,在服务器启动时,Spring容器初始化时,不能通过以下方法获取Spring 容器,细节可以查看spring源码orgspringframeworkwebcontextContextLoader。

以上就是关于spring 怎么获取bean全部的内容,包括:spring 怎么获取bean、spring 中怎么取得bean、Spring Cloud之Ribben:负载均衡实现原理等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/9678818.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-30
下一篇 2023-04-30

发表评论

登录后才能评论

评论列表(0条)

保存