java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > @Autowired可以注入ApplicationContext

使用@Autowired可以注入ApplicationContext

作者:爱吃血肠

这篇文章主要介绍了使用@Autowired可以注入ApplicationContext问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

问题

为何@Autowired可以注入ApplicationContext?

获取applicationContext的方式

(前提是注入applicationContext的一定是交给spring容器处理的bean):

1:

  @Autowired
  ApplicationContext applicationContext;

2:

        
@Component
public class SpringContextUtils implements ApplicationContextAware {
	private static ApplicationContext applicationContext;
 
	public void setApplicationContext(ApplicationContext context) {
		applicationContext = context;
	}
 
	public static ApplicationContext getApplicationContext() {
		if (applicationContext == null)
			throw new IllegalStateException(
					"applicaitonContext未注入,请在applicationContext.xml中定义SpringContextUtil");
		return applicationContext;
	}
 
	public static Object getBean(String name) {
		return applicationContext.getBean(name);
	}
}

      

3:

        
@Component
public class NewSpringContextUtils extends WebApplicationObjectSupport {
	
	public Object getBean(String name){
		return this.getApplicationContext().getBean(name);
	}
	public <T> T  getBean(Class<T> className){
		return this.getApplicationContext().getBean(className);
	}
	public WebApplicationContext getWebApplicationContexts(){
		return this.getWebApplicationContext();
	}
}

      

4:

        
import org.springframework.context.support.ApplicationObjectSupport;
public class NewSpringContextUtils  extends ApplicationObjectSupport{
	public Object getBean(String name){
		return this.getApplicationContext().getBean(name);
	}
	public <T> T  getBean(Class<T> className){
		return this.getApplicationContext().getBean(className);
	}
} 

      

区别:一个耦合了接口一个耦合了注解

为什么需要注入这个ApplicationContext对象呢?

类A(单例的)需要注入一个类B(原型的)

比如你在A类当中的m()方法中返回b,那么无论你调用多少次a.m();返回的都是同一个b对象;就违背b的原型规则,应该在m方法中每次都返回一个新的b;所以某些场景下b不能直接注入;

        
@Component
public class A{
	
	//注意B是原型的  scope=prototype
	@Autowried;
	B b;
	public B m(){
 
		//直接返回注入进来的b;肯定有问题
		//返回的永远是A实例化的时候注入的那个bean
		//违背的B设计成原型的初衷
		return b;
	}
}

      
        
@Component
public class A{
	@Autowired
	ApplicationContext applicationContext;
	public B m(){
		//每次调用m都是通过spring容器去获取b
		//如果b是原型,每次拿到的都是原型b
		B b= applicationContext.getBean("b");
		return b;
	}
}

      

如何查看ApplicationContext 这个对象是否存在spring容器当中?

        
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationContext;
 
/**
 * SprintBootApplication
 */
@Slf4j
@SpringBootApplication
@EnableCaching
public class BootApplication {
 
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(BootApplication.class, args);
        String serverPort = context.getEnvironment().getProperty("server.port");
        Home("mblog started at http://localhost:" + serverPort);
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        //打印spring容器当中所有bean的bd
        for (String beanDefinitionName : beanDefinitionNames) {
            System.out.println(beanDefinitionName);
        }
    }
 
}

spring当中所有的bean输出(结果是不在)

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalPersistenceAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
bootApplication
org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory
storageFactory
aliyunStorageImpl
nativeStorageImpl
qiniuStorageImpl
upYunStorageImpl
springUtils
contextStartup
shiroConfiguration
siteConfiguration
siteOptions
webMvcConfiguration
hibernateFilterAspect
messageEventHandler
postUpdateEventHandler
interceptorHookManager
hidenContentPugin
viewCopyrightPugin
channelServiceImpl
commentServiceImpl
favoriteServiceImpl
linksServiceImpl
mailServiceImpl
messageServiceImpl
openOauthServiceImpl
optionsServiceImpl
permissionServiceImpl
postSearchServiceImpl
postServiceImpl
rolePermissionServiceImpl
roleServiceImpl
securityCodeServiceImpl
tagServiceImpl
userEventServiceImpl
userRoleServiceImpl
userServiceImpl
channelDirective
contentsDirective
controlsDirective
linksDirective
numberDirective
resourceDirective
sidebarDirective
userCommentsDirective
userContentsDirective
userFavoritesDirective
userMessagesDirective
adminController
adminChannelController
adminCommentController
optionsController
permissionController
adminPostController
roleController
themeController
adminUserController
apiController
channelController
indexController
searchController
tagController
callbackController
emailController
forgotController
loginController
logoutController
registerController
commentController
postController
uploadController
favorController
settingsController
usersController
defaultExceptionHandler
jsonUtils
baseInterceptor
menusDirective
subjectFactory
accountRealm
shiroCacheManager
shiroFilterFactoryBean
org.springframework.scheduling.annotation.ProxyAsyncConfiguration
org.springframework.context.annotation.internalAsyncAnnotationProcessor
taskExecutor
fastJsonHttpMessageConverter
org.springframework.cache.annotation.ProxyCachingConfiguration
org.springframework.cache.config.internalCacheAdvisor
cacheOperationSource
cacheInterceptor
org.springframework.boot.autoconfigure.AutoConfigurationPackages
org.springframework.aop.config.internalAutoProxyCreator
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.condition.BeanTypeRegistry
propertySourcesPlaceholderConfigurer
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration$UndertowWebSocketConfiguration
websocketServletWebServerCustomizer
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedUndertow
undertowServletWebServerFactory
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration
servletWebServerFactoryCustomizer
server-org.springframework.boot.autoconfigure.web.ServerProperties
org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor
org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
webServerFactoryCustomizerBeanPostProcessor
errorPageRegistrarBeanPostProcessor
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletConfiguration
dispatcherServlet
spring.http-org.springframework.boot.autoconfigure.http.HttpProperties
spring.mvc-org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration
dispatcherServletRegistration
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration
org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration
taskExecutorBuilder
spring.task.execution-org.springframework.boot.autoconfigure.task.TaskExecutionProperties
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration
defaultValidator
methodValidationPostProcessor
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration
error
beanNameViewResolver
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration
conventionErrorViewResolver
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
errorAttributes
basicErrorController
errorPageCustomizer
preserveErrorControllerTargetClassPostProcessor
spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration
faviconHandlerMapping
faviconRequestHandler
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration
requestMappingHandlerAdapter
requestMappingHandlerMapping
mvcConversionService
mvcValidator
mvcContentNegotiationManager
mvcPathMatcher
mvcUrlPathHelper
viewControllerHandlerMapping
beanNameHandlerMapping
resourceHandlerMapping
mvcResourceUrlProvider
defaultServletHandlerMapping
mvcUriComponentsContributor
httpRequestHandlerAdapter
simpleControllerHandlerAdapter
handlerExceptionResolver
mvcViewResolver
mvcHandlerMappingIntrospector
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
defaultViewResolver
viewResolver
welcomePageHandlerMapping
requestContextFilter
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
hiddenHttpMethodFilter
formContentFilter
org.apache.shiro.spring.config.web.autoconfigure.ShiroWebAutoConfiguration
authenticationStrategy
authenticator
authorizer
subjectDAO
sessionStorageEvaluator
sessionFactory
sessionDAO
sessionManager
securityManager
sessionCookieTemplate
rememberMeManager
rememberMeCookieTemplate
shiroFilterChainDefinition
org.apache.shiro.spring.boot.autoconfigure.ShiroAutoConfiguration
org.apache.shiro.spring.boot.autoconfigure.ShiroBeanAutoConfiguration
lifecycleBeanPostProcessor
eventBus
shiroEventBusAwareBeanPostProcessor
org.apache.shiro.spring.config.web.autoconfigure.ShiroWebFilterConfiguration
filterShiroFilterRegistrationBean
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration
mbeanExporter
objectNamingStrategy
mbeanServer
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration
springApplicationAdminRegistrar
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration$CglibAutoProxyConfiguration
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari
dataSource
org.springframework.boot.autoconfigure.jdbc.DataSourceJmxConfiguration$Hikari
org.springframework.boot.autoconfigure.jdbc.DataSourceJmxConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$PooledDataSourceConfiguration
org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration$HikariPoolDataSourceMetadataProviderConfiguration
hikariPoolDataSourceMetadataProvider
org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker
org.springframework.boot.autoconfigure.jdbc.DataSourceInitializationConfiguration
dataSourceInitializerPostProcessor
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
spring.datasource-org.springframework.boot.autoconfigure.jdbc.DataSourceProperties
org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration$JpaWebConfiguration$JpaWebMvcConfiguration
openEntityManagerInViewInterceptor
org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration$JpaWebConfiguration
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration
transactionManager
jpaVendorAdapter
entityManagerFactoryBuilder
entityManagerFactory
spring.jpa.hibernate-org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties
spring.jpa-org.springframework.boot.autoconfigure.orm.jpa.JpaProperties
dataSourceInitializedPublisher
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration$CacheManagerJpaDependencyConfiguration
org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
cacheManager
ehCacheCacheManager
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
cacheManagerCustomizers
cacheAutoConfigurationValidator
spring.cache-org.springframework.boot.autoconfigure.cache.CacheProperties
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration
persistenceExceptionTranslationPostProcessor
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration
emBeanDefinitionRegistrarPostProcessor
jpaMappingContext
jpaContext
org.springframework.data.jpa.util.JpaMetamodelCacheCleanup
linksRepository
rolePermissionRepository
postResourceRepository
channelRepository
postRepository
favoriteRepository
postAttributeRepository
securityCodeRepository
roleRepository
userOauthRepository
permissionRepository
commentRepository
optionsRepository
resourceRepository
userRepository
messageRepository
tagRepository
postTagRepository
userRoleRepository
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration
gsonBuilder
gson
standardGsonBuilderCustomizer
spring.gson-org.springframework.boot.autoconfigure.gson.GsonProperties
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration
standardJacksonObjectMapperBuilderCustomizer
spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration
jacksonObjectMapperBuilder
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$ParameterNamesModuleConfiguration
parameterNamesModule
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration
jacksonObjectMapper
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
jsonComponentModule
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration
stringHttpMessageConverter
org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration
mappingJackson2HttpMessageConverter
org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration
org.springframework.boot.autoconfigure.http.GsonHttpMessageConvertersConfiguration
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration
messageConverters
org.springframework.data.web.config.ProjectingArgumentResolverRegistrar
projectingArgumentResolverBeanPostProcessor
org.springframework.data.web.config.SpringDataWebConfiguration
pageableResolver
sortResolver
org.springframework.data.web.config.SpringDataJacksonConfiguration
jacksonGeoModule
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration
pageableCustomizer
sortCustomizer
spring.data.web-org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration$JdbcTemplateConfiguration
jdbcTemplate
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration$NamedParameterJdbcTemplateConfiguration
namedParameterJdbcTemplate
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration
spring.jdbc-org.springframework.boot.autoconfigure.jdbc.JdbcProperties
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration$FlywayJdbcOperationsDependencyConfiguration
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration$FlywayJpaDependencyConfiguration
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration$FlywayConfiguration$FlywayInitializerJdbcOperationsDependencyConfiguration
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration$FlywayConfiguration$FlywayInitializerJpaDependencyConfiguration
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration$FlywayConfiguration
flyway
flywayInitializer
spring.flyway-org.springframework.boot.autoconfigure.flyway.FlywayProperties
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration
stringOrNumberMigrationVersionConverter
flywayDefaultDdlModeProvider
org.springframework.boot.autoconfigure.freemarker.FreeMarkerServletWebConfiguration
freeMarkerConfigurer
freeMarkerConfiguration
freeMarkerViewResolver
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration
spring.freemarker-org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration
h2Console
spring.h2.console-org.springframework.boot.autoconfigure.h2.H2ConsoleProperties
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration$LoggingCodecConfiguration
loggingCodecCustomizer
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration$JacksonCodecConfiguration
jacksonCodecCustomizer
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties
org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration
taskSchedulerBuilder
spring.task.scheduling-org.springframework.boot.autoconfigure.task.TaskSchedulingProperties
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration$DataSourceTransactionManagerConfiguration
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration
org.springframework.transaction.config.internalTransactionAdvisor
transactionAttributeSource
transactionInterceptor
org.springframework.transaction.config.internalTransactionalEventListenerFactory
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration$EnableTransactionManagementConfiguration$CglibAutoProxyConfiguration
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration$EnableTransactionManagementConfiguration
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration$TransactionTemplateConfiguration
transactionTemplate
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration
platformTransactionManagerCustomizers
spring.transaction-org.springframework.boot.autoconfigure.transaction.TransactionProperties
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration
restTemplateBuilder
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration$UndertowWebServerFactoryCustomizerConfiguration
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration$UndertowWebServerFactoryCustomizerConfiguration
undertowWebServerFactoryCustomizer
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration
characterEncodingFilter
localeCharsetMappingsCustomizer
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration
multipartConfigElement
multipartResolver
spring.servlet.multipart-org.springframework.boot.autoconfigure.web.servlet.MultipartProperties
org.springframework.boot.devtools.autoconfigure.DevToolsDataSourceAutoConfiguration$DatabaseShutdownExecutorJpaDependencyConfiguration
org.springframework.boot.devtools.autoconfigure.DevToolsDataSourceAutoConfiguration
inMemoryDatabaseShutdownExecutor
org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration$RestartConfiguration
classPathFileSystemWatcher
classPathRestartStrategy
hateoasObjenesisCacheDisabler
fileSystemWatcherFactory
conditionEvaluationDeltaLoggingListener
org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration$LiveReloadConfiguration
liveReloadServer
optionalLiveReloadServer
liveReloadServerEventListener
org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration
spring.devtools-org.springframework.boot.devtools.autoconfigure.DevToolsProperties
org.springframework.orm.jpa.SharedEntityManagerCreator#0

如何查看单例池中是否有这个ApplicationContext对象?

debug
DefaultSingletonBeanRegistry  addSingleton

在单例池中就可autowired装配

@Autowried这个注解功能的类是 AutowiredAnnotationBeanPostProcessor

spring源码有一个ReflectionUtils反射工具类

他喵的

是spring新版本支持的嘛?我看源码metadata.inject(bean, beanName, pvs)方法实现里没看见这个

beanFactory.resolveDependency,我在springboot2.1.2这里看的,没看见实现

说白了没啥区别,都是在后置处理器里注入了ApplicationContext,实现ApplicationContextAware接口是ApplicationContextAwareProcessor这个后置处理器里显式的调用setApplication方法注入的,而@Autoware也是后置处理器注入,只不过是AutowiredAnnotationBeanPostProcessor这个后置处理器在属性填充的时候注入,其实spring百分之80工作都是后置处理器完成的

调式项目修改端口号

server:
    port: 8088
    use-forward-headers: true
    undertow:
        io-threads: 2
        worker-threads: 32
        buffer-size: 1024
        directBuffers: true

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文