복붙노트

[SPRING] 외부 파일의 속성을 hibernate.cfg.xml에 포함시키는 방법?

SPRING

외부 파일의 속성을 hibernate.cfg.xml에 포함시키는 방법?

나는 src | main | java | dbConnection.properties에 데이터베이스 구성 등록 정보를 저장하고 jstl 표현식의 형태로 hibernate.cfg.xml에 포함시킬 수 있어야합니다. (예 : $ {password} 등). 그것을하는 방법?

현재 hibernate.cfg.xml :

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
<property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">postgres</property>
        <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
    </session-factory>
</hibernate-configuration>

나는 이런 것을 필요로한다.

<?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD//EN"
            "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
        <session-factory>
    <property name="connection.driver_class">${DRIVER}</property>
            <property name="connection.username">${USERNAME}</property>
            <property name="connection.password">${PASSWORD}</property>
            <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
        </session-factory>
    </hibernate-configuration>

해결법

  1. ==============================

    1.여러분은 Spring을 사용한다고 말하면서 Spring이 모든 노력을 기울이지 않도록하십시오. 속성 자리 표시자를 원하는 자리 표시 자로 바꿉니다.

    여러분은 Spring을 사용한다고 말하면서 Spring이 모든 노력을 기울이지 않도록하십시오. 속성 자리 표시자를 원하는 자리 표시 자로 바꿉니다.

    <context:property-placeholder location="classpath:dbConnection.properties" />
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="hibernateProperties">
           <map>
                <entry key="connection.driver_class" value="${DRIVER}" />
                <entry key="connection.username" value="${USERNAME}" />
                <entry key="connection.password" value="${PASSWORD}" />
                <entry key="transaction.factory_class" value="org.hibernate.transaction.JDBCTransactionFactory" />
            </map>
        <property>
     </bean>
    

    프로덕션 환경에서 사용하도록 권장되지 않은 내부 절전 연결 항목을 사용하는 대신 무료 조언은 Spring의 데이터 소스를 구성하고 LocalSessionFactoryBean에 연결합니다.

  2. ==============================

    2.프로그래밍 방식으로 할 수 있습니다.

    프로그래밍 방식으로 할 수 있습니다.

    hibernate.cfg.xml은 다음과 같아야합니다.

    <?xml version='1.0' encoding='utf-8'?>
        <!DOCTYPE hibernate-configuration PUBLIC
                "-//Hibernate/Hibernate Configuration DTD//EN"
                "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
        <hibernate-configuration>
            <session-factory>
                <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
            </session-factory>
        </hibernate-configuration>
    

    dbConnection.properties

    connection.driver_class=org.postgresql.Driver
    connection.username=postgres
    connection.password=postgres
    

    그리고 SessionFactory를 만들 때 다음을 할 수 있습니다.

    Properties dbConnectionProperties = new Properties();
    try {
        dbConnectionProperties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("dbConnection.properties"));
    } catch(Exception e) {
        // Log
    }
    
    SessionFactory sessionFactory = new Configuration().mergeProperties(dbConnectionProperties).configure().buildSessionFactory();
    
  3. ==============================

    3.다음은 hibernate.cfg.xml 파일의 플레이스 홀더를 프로퍼티 파일의 프로퍼티로 대체 / 필터하는 다음의 Maven 설정을 보았다.

    다음은 hibernate.cfg.xml 파일의 플레이스 홀더를 프로퍼티 파일의 프로퍼티로 대체 / 필터하는 다음의 Maven 설정을 보았다.

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
                <executions>
    
                    <execution>
                        <id>copy-resources</id>
                        <!-- here the phase you need -->
                        <phase>validate</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/target/extra-resources</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>src/main/resources</directory>
                                    <filtering>true</filtering>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
    
            </plugin>
        </plugins>
    
        <!-- Specify the file that contains the value to replace the placeholders -->
        <filters>
            <filter>src/main/resources/dbConnection.properties</filter>
        </filters>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <excludes>
                    <exclude>*</exclude>
                </excludes>
                <includes>
                    <include>hibernate.cfg.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
    

    이 구성을 사용하면 유효성 검사 Maven 목표를 실행하여 필터링 된 파일을 생성하고 파일이 올바르게 재배치되었는지 확인할 수 있습니다

    이것은 Maven을 사용하는 경우에 유용합니다.

  4. from https://stackoverflow.com/questions/24176024/how-to-include-properties-from-external-file-to-hibernate-cfg-xml by cc-by-sa and MIT license