欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用@Autowired可以注入ApplicationContext

 更新時間:2024年06月04日 09:43:11   作者:愛吃血腸  
這篇文章主要介紹了使用@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);
	}
} 

      

區(qū)別:一個耦合了接口一個耦合了注解

為什么需要注入這個ApplicationContext對象呢?

類A(單例的)需要注入一個類B(原型的)

比如你在A類當(dāng)中的m()方法中返回b,那么無論你調(diào)用多少次a.m();返回的都是同一個b對象;就違背b的原型規(guī)則,應(yīng)該在m方法中每次都返回一個新的b;所以某些場景下b不能直接注入;

  • 錯誤:
        
@Component
public class A{
	
	//注意B是原型的  scope=prototype
	@Autowried;
	B b;
	public B m(){
 
		//直接返回注入進來的b;肯定有問題
		//返回的永遠是A實例化的時候注入的那個bean
		//違背的B設(shè)計成原型的初衷
		return b;
	}
}

      
  • 正確:
        
@Component
public class A{
	@Autowired
	ApplicationContext applicationContext;
	public B m(){
		//每次調(diào)用m都是通過spring容器去獲取b
		//如果b是原型,每次拿到的都是原型b
		B b= applicationContext.getBean("b");
		return b;
	}
}

      

如何查看ApplicationContext 這個對象是否存在spring容器當(dāng)中?

        
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容器當(dāng)中所有bean的bd
        for (String beanDefinitionName : beanDefinitionNames) {
            System.out.println(beanDefinitionName);
        }
    }
 
}

spring當(dāng)中所有的bean輸出(結(jié)果是不在)

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

  • postProcessProperties()方法用來處理屬性注入
  • metadata.inject(bean, beanName, pvs);屬性注入

spring源碼有一個ReflectionUtils反射工具類

他喵的

是spring新版本支持的嘛?我看源碼metadata.inject(bean, beanName, pvs)方法實現(xiàn)里沒看見這個

beanFactory.resolveDependency,我在springboot2.1.2這里看的,沒看見實現(xiàn)

說白了沒啥區(qū)別,都是在后置處理器里注入了ApplicationContext,實現(xiàn)ApplicationContextAware接口是ApplicationContextAwareProcessor這個后置處理器里顯式的調(diào)用setApplication方法注入的,而@Autoware也是后置處理器注入,只不過是AutowiredAnnotationBeanPostProcessor這個后置處理器在屬性填充的時候注入,其實spring百分之80工作都是后置處理器完成的

調(diào)式項目修改端口號

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

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論