码迷,mamicode.com
首页 > 其他好文 > 详细

[Sprint] Properties for project configuration

时间:2018-09-02 15:04:26      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:tor   mys   turn   ecif   spl   location   ann   ide   findall   

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

标签:tor   mys   turn   ecif   spl   location   ann   ide   findall   

原文地址:https://www.cnblogs.com/Answer1215/p/9573811.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!