简体   繁体   English

将配置从XML更改为注释

[英]Change Configuration from XML to annotations

I want to edit this settings to annotations way 我想将此设置编辑为注释方式
Because I want to save these variable in a file(It will store all dynamic variables the code needed) 因为我想将这些变量保存在文件中(它将存储所有动态变量所需的代码)
I will use one java function read these variable dynamically 我将使用一个Java函数动态读取这些变量
But I am not familiar with it 但是我不熟悉

xxx.property xxx.property

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

model-config.xml 模型-config.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>
    .....

What can I do ? 我能做什么 ?

Which kyewords should I search? 我应该搜索哪些关键词?

You can do it with a configuration class, using @Configuration annotation, that uses annotations to handle all the configurations, here's an example of what you need: 您可以使用配置类(使用@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"));
         }
      };
   }
}

For further information you can take a look at: 有关更多信息,请查看:

  1. Hibernate 3 with Spring configuration Tutorial Hibernate 3 with Spring配置教程
  2. AnnotationSessionFactoryBean AnnotationSessionFactoryBean
  3. Spring - Java Based Configuration Spring-基于Java的配置

While switching to Annotation is the way to go, there is another way to do it without switching, if that eases your work. 切换到注释是一种方法,但如果不这样做,那么还有另一种无需切换的方法。 You might have to define a bean and pass it the name of your property file (assuming its kept in classpath) 您可能需要定义一个bean并将其传递给您的属性文件的名称(假设其保存在classpath中)

<bean 
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

        <property name="location">
            <value>YOURPROPERTY.properties</value>
        </property>
    </bean>

Ones you have this in place you can change your bean definition like this 有了这个,您可以像这样更改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>

What we did here is, we have asked spring to load and keep the property file using PropertyPlaceholderConfigurer and the use the key in your bean definitions using this ${YOURKEY} specifier. 我们在这里所做的是,我们已经要求spring使用PropertyPlaceholderConfigurer加载并保留属性文件,并使用此${YOURKEY}说明符在bean定义中使用键。

As I understood, you want convert model-config.xml to annotation based configurations. 据我了解,您希望将model-config.xml转换为基于注释的配置。 For this purpose you will need to create @Configuration class in which you will declare bean and will set properties pragmatically. 为此,您将需要创建@Configuration类,在其中声明bean并以实用的方式设置属性。 This @Configuration class should look like this: @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

}

You can find setters for respective xml properties here and here 您可以在此处此处找到相应xml属性的设置器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM