[Sprint] Properties for project configuration

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Sprint] Properties for project configuration相关的知识,希望对你有一定的参考价值。

We might have some project specific configuration need to setup. The good approach to do this in Sprint is using ‘Proptries‘.

 

In resouces/applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">


    <context:annotation-config />
    <!-- Load app.properties file for use -->
    <context:property-placeholder location="app.properties" />

    <bean name="customerRepository" class="com.pluralsight.repository.HibernateCustomerRepositoryImpl"></bean>



    <context:component-scan base-package="com.pluralsight" />
</beans>

 

In xml, we tell Sprint to looking for a file call ‘app.properties‘, which should located in the same folder of applicationContext.xml.

Inside app.properties file we can define some variables which related to the project:

dbUsername=mysqlusername

 

we can inject those variable into class:

public class HibernateCustomerRepositoryImpl implements CustomerRepository {

    @Value("${dbUsername}")
    private String dbUsername;
    
    @Override
    public List<Customer> findAll() {

        system.out.println(dbUsername)
    }
}

 

 

****

 

We can also configure the ‘properties‘ by using Java configuration:

in com/pluralsight/AppConfig.java:

package com.pluralsight;

import com.pluralsight.repository.CustomerRepository;
import com.pluralsight.repository.HibernateCustomerRepositoryImpl;
import com.pluralsight.service.CustomerService;
import com.pluralsight.service.CustomerServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan({"com.pluralsight"})
public class AppConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurationn() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

 

以上是关于[Sprint] Properties for project configuration的主要内容,如果未能解决你的问题,请参考以下文章

[Java Sprint] AutoWire

C sprint change 左对齐宽度

[Java Sprint] Spring XML Configuration : Constructor Injection Demo

C语言中的sprint函数问题

Common Macros for Build Commands and Properties

FCC 练习笔记 Testing Objects for Properties