【问题标题】:Change Configuration from XML to annotations将配置从 XML 更改为注释
【发布时间】:2015-06-26 06:49:17
【问题描述】:

我想将此设置编辑为注释方式
因为我想将这些变量保存在一个文件中(它将存储代码所需的所有动态变量)
我将使用一个 java 函数动态读取这些变量
但我不熟悉它

xxx.property

IP = com.mysql.jdbc.Driver
user = root
password = 1234

模型配置.xml

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass">
        <value>com.mysql.jdbc.Driver</value>
    </property>
    <property name="jdbcUrl">
        <value>IP</value>
    </property>
    <property name="user">
        <value>user</value>
    </property>
    <property name="password">
        <value>password</value>
    </property>
</bean>



    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="mappingLocations">
        <list>
            <value>classpath:/com/test/User.hbm.xml</value>
        </list>
    </property>
    .....

我能做什么?

我应该搜索哪些关键词?

【问题讨论】:

    标签: java spring hibernate annotations


    【解决方案1】:

    您可以使用配置类来完成,使用 @Configuration 注释,它使用注释来处理所有配置,这是您需要的示例:

    @Configuration
    @EnableTransactionManagement
    @PropertySource({ "classpath:persistence-mysql.properties" })
    @ComponentScan({ "package.persistence" }) //You specify the package of your entities here
    public class SpringHibernateConfig {
    
       @Autowired
       private Environment env;
    
      @Bean
      public AnnotationSessionFactoryBean sessionFactory() {
          AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();
          sessionFactory.setDataSource(restDataSource());
          // You specify your models package to be scanned by Hibernate
          sessionFactory.setPackagesToScan(new String[] { "package.model" });
          sessionFactory.setHibernateProperties(hibernateProperties());
    
          return sessionFactory;
       }
    
    
       // You configure your jdbc settings here
       @Bean
       public DataSource restDataSource() {
          BasicDataSource dataSource = new BasicDataSource();
          dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
          dataSource.setUrl(env.getProperty("com.mysql.jdbc.Driver"));
          dataSource.setUsername(env.getProperty("root"));
          dataSource.setPassword(env.getProperty("1234"));
    
          return dataSource;
       }
    
       @Bean
       @Autowired
       public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
          HibernateTransactionManager txManager = new HibernateTransactionManager();
          txManager.setSessionFactory(sessionFactory);
          return txManager;
       }
    
       @Bean
       public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
          return new PersistenceExceptionTranslationPostProcessor();
       }
    
       // You specify Hibernate properties here
       Properties hibernateProperties() {
          return new Properties() {
             {
                setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
                setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
             }
          };
       }
    }
    

    有关更多信息,您可以查看:

    1. Hibernate 3 with Spring configuration Tutorial
    2. AnnotationSessionFactoryBean
    3. Spring - Java Based Configuration

    【讨论】:

      【解决方案2】:

      虽然切换到 Annotation 是一种可行的方法,但如果这样可以简化您的工作,还有另一种无需切换的方法。您可能必须定义一个 bean 并将您的属性文件的名称传递给它(假设它保存在类路径中)

      <bean 
              class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      
              <property name="location">
                  <value>YOURPROPERTY.properties</value>
              </property>
          </bean>
      

      如果你有这个,你可以像这样改变你的 bean 定义

      <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
      <property name="driverClass">
          <value>${IP}</value>
      </property>
      <property name="jdbcUrl">
          <value>IP</value>
      </property>
      <property name="user">
          <value>${user}</value>
      </property>
      <property name="password">
          <value>${password}</value>
      </property>
      

      我们在这里所做的是,我们要求 spring 使用 PropertyPlaceholderConfigurer 加载并保留属性文件,并使用 ${YOURKEY} 说明符在 bean 定义中使用键。

      【讨论】:

      • 你可以把它放在资源文件夹中。或您的类路径中的任何文件夹。
      【解决方案3】:

      据我了解,您希望将 model-config.xml 转换为基于注释的配置。为此,您将需要创建 @Configuration 类,您将在其中声明 bean 并务实地设置属性。这个@Configuration 类应该是这样的:

      @EnableWebMvc 
      @ComponentScan(basePackages = {"org.some.package"}) 
      @Configuration
      public class AppConfig extends WebMvcConfigurerAdapter {
      
          @Bean(name="dataSource") 
          public ComboPooledDataSource getDataSource() {
      
              // Read your properties
              Properties prop = new Properties();
              String propFileName = "xxx.property";
      
              InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
      
              if (inputStream != null) {
                  prop.load(inputStream);
              } else {
                  throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
              }
      
      
              ComboPooledDataSource cpds = new ComboPooledDataSource();
      
              cpds.setDriverClass(prop.getProperty("IP")); //?? IP = com.mysql.jdbc.Driver ??
              cpds.setJdbcUrl(prop.getProperty("propertyForUrl"));
              cpds.setUser(prop.getProperty("user"));
              cpds.setPassword(prop.getProperty("password"));
      
              return cpds;
          }
      
          //create the similar function for sessionFactory
      
      }
      

      您可以找到相应 xml 属性 herehere 的设置器

      【讨论】:

      • basePackages = {"org.some.package"} basePackages 是什么意思?属性文件保存在哪里??
      • 相当于你的model-config.xml中的&lt;context:component-scan base-package="org.company.package"/&gt;
      • 如果我使用 ComboPooledDataSource,它会抛出 org.hibernate.service.UnknownUnwrapTypeException: Cannot unwrap to requested type [javax.sql.DataSource]
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      • 1970-01-01
      相关资源
      最近更新 更多