Рубрики
Без рубрики

Весна – Как получить доступ к источнику сообщений в компоненте (messagesourceaware)

– Весна – Как получить доступ к источнику сообщений в компоненте (messagesourceaware)

В последнем уроке вы можете получить Источник сообщения через ApplicationContext . Но для того, чтобы компонент получил источник сообщения, вам необходимо реализовать интерфейс MessageSourceAware .

Пример

Класс Customer Service , реализующий интерфейс MessageSourceAware , имеет метод настройки для установки свойства MessageSource .

package com.mkyong.customer.services;

import java.util.Locale;

import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;

public class CustomerService implements MessageSourceAware
{
	private MessageSource messageSource;
	
	public void setMessageSource(MessageSource messageSource) {
		this.messageSource = messageSource;
	}
	
	public void printMessage(){
		String name = messageSource.getMessage("customer.name", 
    			new Object[] { 28, "http://www.mkyong.com" }, Locale.US);

    	System.out.println("Customer name (English) : " + name);
    	
    	String namechinese = messageSource.getMessage("customer.name", 
    			new Object[] { 28, "http://www.mkyong.com" }, 
                        Locale.SIMPLIFIED_CHINESE);

    	System.out.println("Customer name (Chinese) : " + namechinese);
	}
	
}

Запустите его

package com.mkyong.common;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class App 
{
    public static void main( String[] args )
    {
    	ApplicationContext context = 
    		new ClassPathXmlApplicationContext(
			    new String[] {"locale.xml","Spring-Customer.xml"});
 
    	CustomerService cust = (CustomerService)context.getBean("customerService");
    	cust.printMessage();
    }
}

Оригинал: “https://mkyong.com/spring/spring-how-to-access-messagesource-in-bean-messagesourceaware/”