Java 如何在Spring容器中添加环境bean?
我正在学习使用Java配置的Spring MVC和Hibernate,我有以下代码:Java 如何在Spring容器中添加环境bean?,java,hibernate,spring-mvc,Java,Hibernate,Spring Mvc,我正在学习使用Java配置的Spring MVC和Hibernate,我有以下代码: @Configuration @ComponentScan("com.dgs.springdemo") @EnableWebMvc @EnableTransactionManagement @PropertySource({"classpath:persistence-mysql.properties"}) public class WebAppConfig implements WebMvcConfigure
@Configuration
@ComponentScan("com.dgs.springdemo")
@EnableWebMvc
@EnableTransactionManagement
@PropertySource({"classpath:persistence-mysql.properties"})
public class WebAppConfig implements WebMvcConfigurer {
@Autowired
private Environment env;
private Logger logger = Logger.getLogger(getClass());
@Bean
public InternalResourceViewResolver viewResolver() {
// create view resolver
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
// set properties on view resolver
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Bean
public DataSource myDataSource() {
// create connection pool
ComboPooledDataSource myDataSource = new ComboPooledDataSource();
// set the jdbc driver
try {
myDataSource.setDriverClass("com.mysql.jdbc.Driver");
}
catch (PropertyVetoException exc) {
throw new RuntimeException(exc);
}
// for sanity's sake, let's log url and user ... just to make sure we are reading the data
logger.info("jdbc.url=" + env.getProperty("jdbc.url"));
logger.info("jdbc.user=" + env.getProperty("jdbc.user"));
// set database connection props
myDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
myDataSource.setUser(env.getProperty("jdbc.user"));
myDataSource.setPassword(env.getProperty("jdbc.password"));
// set connection pool props
myDataSource.setInitialPoolSize(Integer.parseInt(env.getProperty("connection.pool.initialPoolSize")));
myDataSource.setMinPoolSize(Integer.parseInt(env.getProperty("connection.pool.minPoolSize")));
myDataSource.setMaxPoolSize(Integer.parseInt(env.getProperty("connection.pool.maxPoolSize")));
myDataSource.setMaxIdleTime(Integer.parseInt(env.getProperty("connection.pool.maxIdleTime")));
return myDataSource;
}
private Properties getHibernateProperties() {
// set hibernate properties
Properties props = new Properties();
props.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
props.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
return props;
}
@Bean
public LocalSessionFactoryBean sessionFactory(){
// create session factorys
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
// set the properties
sessionFactory.setDataSource(myDataSource());
sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan"));
sessionFactory.setHibernateProperties(getHibernateProperties());
return sessionFactory;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
// setup transaction manager based on session factory
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
}
我看到在这个类中注入了环境bean。我想知道这个bean是如何添加到Spring容器中的?谁加的
这是pom文件:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dgs</groupId>
<artifactId>SpringMVCHibernateXML</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>SpringMVCHibernateXML Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<springframework.version>5.0.2.RELEASE</springframework.version>
<hibernate.version>5.4.2.Final</hibernate.version>
<mysql.connector.version>8.0.12</mysql.connector.version>
<c3po.version>0.9.5.2</c3po.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- Spring MVC support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Servlet, JSP and JSTL support -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- C3PO -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>${c3po.version}</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>SpringMVCHibernateXML</finalName>
<pluginManagement>
<plugins>
<plugin>
<!-- Add Maven coordinates (GAV) for: maven-war-plugin -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Environment
是一个框架级bean,它的精确类型和创建取决于所使用的Spring组件
您正在使用SpringWeb,因此它很可能是由方法创建的StandardServleteEnvironment
bean。当servlet由servlet容器初始化时,应该调用该函数。其他设置将以不同方式进行,例如,Spring Boot将在SpringApplication.prepareEnvironment()
private方法中创建StandardEnvironment
bean
如果您想了解它是如何在特定设置中创建的,您需要调试应用程序启动。谢谢Karol。你能告诉我为什么在Spring容器中看不到这个bean吗?我正在使用applicationContext.getBeanDefinitionNames(),但我看不到StandardServleteEnvironment bean。不确定,可能是因为在创建
环境bean之前,您在生命周期中做得太早,或者您有多个应用程序上下文?从容器生命周期后期的某个地方开始,autowireBeanFactory
并使用GetBeanSoftType(Environment.class)
org.springframework.context.annotation.internalConfigurationAnnotationProcessor : class org.springframework.context.annotation.ConfigurationClassPostProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor : class org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor : class org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor : class org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
org.springframework.context.annotation.internalPersistenceAnnotationProcessor : class org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor
org.springframework.context.event.internalEventListenerProcessor : class org.springframework.context.event.EventListenerMethodProcessor
org.springframework.context.event.internalEventListenerFactory : class org.springframework.context.event.DefaultEventListenerFactory
webAppConfig : class com.dgs.springdemo.config.WebAppConfig$$EnhancerBySpringCGLIB$$b1e6ba9c
customerController : class com.dgs.springdemo.controller.CustomerController
org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration : class org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$9f4728e5
requestMappingHandlerMapping : class org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
mvcPathMatcher : class org.springframework.util.AntPathMatcher
mvcUrlPathHelper : class org.springframework.web.util.UrlPathHelper
mvcContentNegotiationManager : class org.springframework.web.accept.ContentNegotiationManager
viewControllerHandlerMapping : class org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport$EmptyHandlerMapping
beanNameHandlerMapping : class org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping
resourceHandlerMapping : class org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport$EmptyHandlerMapping
mvcResourceUrlProvider : class org.springframework.web.servlet.resource.ResourceUrlProvider
defaultServletHandlerMapping : class org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport$EmptyHandlerMapping
requestMappingHandlerAdapter : class org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
mvcConversionService : class org.springframework.format.support.DefaultFormattingConversionService
mvcValidator : class org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport$NoOpValidator
mvcUriComponentsContributor : class org.springframework.web.method.support.CompositeUriComponentsContributor
httpRequestHandlerAdapter : class org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter
simpleControllerHandlerAdapter : class org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter
handlerExceptionResolver : class org.springframework.web.servlet.handler.HandlerExceptionResolverComposite
mvcViewResolver : class org.springframework.web.servlet.view.ViewResolverComposite
mvcHandlerMappingIntrospector : class org.springframework.web.servlet.handler.HandlerMappingIntrospector
org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration : class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$da8643af
org.springframework.transaction.config.internalTransactionAdvisor : class org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor
transactionAttributeSource : class org.springframework.transaction.annotation.AnnotationTransactionAttributeSource
transactionInterceptor : class org.springframework.transaction.interceptor.TransactionInterceptor
org.springframework.transaction.config.internalTransactionalEventListenerFactory : class org.springframework.transaction.event.TransactionalEventListenerFactory
viewResolver : class org.springframework.web.servlet.view.InternalResourceViewResolver
myDataSource : class com.mchange.v2.c3p0.ComboPooledDataSource
sessionFactory : class org.hibernate.internal.SessionFactoryImpl
transactionManager : class org.springframework.orm.hibernate5.HibernateTransactionManager
org.springframework.aop.config.internalAutoProxyCreator : class org.springframework.aop.framework.autoproxy.InfrastructureAdvisorAutoProxyCreator