org.springframework.context.MessageSource Java Examples

The following examples show how to use org.springframework.context.MessageSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MessageSourceUtil.java    From AsuraFramework with Apache License 2.0 6 votes vote down vote up
/**
 * 查找错误消息
 *
 * @param source
 * @param code
 * @param params
 * @param defaultMsg
 *
 * @return
 */
public static String getChinese(MessageSource source, String code, Object[] params, String defaultMsg) {
    if (Check.isNull(source)) {
        throw new IllegalArgumentException("message source is null");
    }
    if (Check.isNullOrEmpty(code)) {
        throw new IllegalArgumentException("code is empty");
    }
    //如果没有object 默认设置为空数组
    if (Check.isNull(params)) {
        params = new Object[]{};
    }
    if (Check.isNullOrEmpty(defaultMsg)) {
        return source.getMessage(code, params, Locale.SIMPLIFIED_CHINESE);
    } else {
        return source.getMessage(code, params, defaultMsg, Locale.SIMPLIFIED_CHINESE);
    }
}
 
Example #2
Source File: JstlUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Checks JSTL's "javax.servlet.jsp.jstl.fmt.localizationContext"
 * context-param and creates a corresponding child message source,
 * with the provided Spring-defined MessageSource as parent.
 * @param servletContext the ServletContext we're running in
 * (to check JSTL-related context-params in {@code web.xml})
 * @param messageSource the MessageSource to expose, typically
 * the ApplicationContext of the current DispatcherServlet
 * @return the MessageSource to expose to JSTL; first checking the
 * JSTL-defined bundle, then the Spring-defined MessageSource
 * @see org.springframework.context.ApplicationContext
 */
public static MessageSource getJstlAwareMessageSource(
		@Nullable ServletContext servletContext, MessageSource messageSource) {

	if (servletContext != null) {
		String jstlInitParam = servletContext.getInitParameter(Config.FMT_LOCALIZATION_CONTEXT);
		if (jstlInitParam != null) {
			// Create a ResourceBundleMessageSource for the specified resource bundle
			// basename in the JSTL context-param in web.xml, wiring it with the given
			// Spring-defined MessageSource as parent.
			ResourceBundleMessageSource jstlBundleWrapper = new ResourceBundleMessageSource();
			jstlBundleWrapper.setBasename(jstlInitParam);
			jstlBundleWrapper.setParentMessageSource(messageSource);
			return jstlBundleWrapper;
		}
	}
	return messageSource;
}
 
Example #3
Source File: WebErrorHandlers.java    From errors-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
/**
 * To initialize the {@link WebErrorHandlers} instance with a code-to-message translator, a
 * non-empty collection of {@link WebErrorHandler} implementations and an optional fallback
 * error handler.
 *
 * <p>This constructor is meant to be called by {@link WebErrorHandlersBuilder#build()} method.
 *
 * @param messageSource                 The code to message translator.
 * @param webErrorHandlers              Collection of {@link WebErrorHandler} implementations.
 * @param defaultWebErrorHandler        Fallback web error handler.
 * @param exceptionRefiner              Possibly can refine exceptions before handling them.
 * @param exceptionLogger               Logs exceptions.
 * @param webErrorHandlerPostProcessors Executes additional actions on HttpError.
 * @param fingerprintProvider           Calculates fingerprint of error message.
 * @param errorsProperties              Configuration properties bean.
 * @throws NullPointerException     When one of the required parameters is null.
 * @throws IllegalArgumentException When the collection of implementations is empty.
 */
WebErrorHandlers(@NonNull MessageSource messageSource,
                 @NonNull List<WebErrorHandler> webErrorHandlers,
                 @Nullable WebErrorHandler defaultWebErrorHandler,
                 @NonNull ExceptionRefiner exceptionRefiner,
                 @NonNull ExceptionLogger exceptionLogger,
                 @NonNull List<WebErrorHandlerPostProcessor> webErrorHandlerPostProcessors,
                 @NonNull FingerprintProvider fingerprintProvider,
                 @NonNull ErrorsProperties errorsProperties) {
    this.errorsProperties = requireNonNull(errorsProperties);
    this.messageSource = new TemplateAwareMessageSource(
        requireNonNull(messageSource, "We need a MessageSource implementation to message translation"));
    this.webErrorHandlers = requireAtLeastOneHandler(webErrorHandlers);
    if (defaultWebErrorHandler != null) this.defaultWebErrorHandler = defaultWebErrorHandler;
    this.exceptionRefiner = requireNonNull(exceptionRefiner);
    this.exceptionLogger = requireNonNull(exceptionLogger);
    this.webErrorHandlerPostProcessors = requireNonNull(webErrorHandlerPostProcessors);
    this.fingerprintProvider = requireNonNull(fingerprintProvider);
}
 
Example #4
Source File: RequestContext.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public RequestContext(ServerWebExchange exchange, Map<String, Object> model, MessageSource messageSource,
		@Nullable RequestDataValueProcessor dataValueProcessor) {

	Assert.notNull(exchange, "ServerWebExchange is required");
	Assert.notNull(model, "Model is required");
	Assert.notNull(messageSource, "MessageSource is required");
	this.exchange = exchange;
	this.model = model;
	this.messageSource = messageSource;

	LocaleContext localeContext = exchange.getLocaleContext();
	Locale locale = localeContext.getLocale();
	this.locale = (locale != null ? locale : Locale.getDefault());
	TimeZone timeZone = (localeContext instanceof TimeZoneAwareLocaleContext ?
			((TimeZoneAwareLocaleContext) localeContext).getTimeZone() : null);
	this.timeZone = (timeZone != null ? timeZone : TimeZone.getDefault());

	this.defaultHtmlEscape = null;  // TODO
	this.dataValueProcessor = dataValueProcessor;
}
 
Example #5
Source File: LoadedMessageSourceService.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
   public MessageSource getMessageService(String messageFilename) {
if (messageFilename != null) {
    MessageSource ms = messageServices.get(messageFilename);
    if (ms == null) {
	ResourceBundleMessageSource rbms = (ResourceBundleMessageSource) beanFactory
		.getBean(LOADED_MESSAGE_SOURCE_BEAN);
	rbms.setBasename(messageFilename);
	messageServices.put(messageFilename, rbms);
	ms = rbms;
    }
    return ms;
} else {
    return null;
}
   }
 
Example #6
Source File: JstlUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks JSTL's "javax.servlet.jsp.jstl.fmt.localizationContext"
 * context-param and creates a corresponding child message source,
 * with the provided Spring-defined MessageSource as parent.
 * @param servletContext the ServletContext we're running in
 * (to check JSTL-related context-params in {@code web.xml})
 * @param messageSource the MessageSource to expose, typically
 * the ApplicationContext of the current DispatcherServlet
 * @return the MessageSource to expose to JSTL; first checking the
 * JSTL-defined bundle, then the Spring-defined MessageSource
 * @see org.springframework.context.ApplicationContext
 */
public static MessageSource getJstlAwareMessageSource(
		ServletContext servletContext, MessageSource messageSource) {

	if (servletContext != null) {
		String jstlInitParam = servletContext.getInitParameter(Config.FMT_LOCALIZATION_CONTEXT);
		if (jstlInitParam != null) {
			// Create a ResourceBundleMessageSource for the specified resource bundle
			// basename in the JSTL context-param in web.xml, wiring it with the given
			// Spring-defined MessageSource as parent.
			ResourceBundleMessageSource jstlBundleWrapper = new ResourceBundleMessageSource();
			jstlBundleWrapper.setBasename(jstlInitParam);
			jstlBundleWrapper.setParentMessageSource(messageSource);
			return jstlBundleWrapper;
		}
	}
	return messageSource;
}
 
Example #7
Source File: JsonResult.java    From match-trade with Apache License 2.0 6 votes vote down vote up
/**
 * <p>返回失败,无数据</p>
 * @param BindingResult
 * @return JsonResult
 */
public JsonResult<T> error(BindingResult result, MessageSource messageSource) {
    StringBuffer msg = new StringBuffer();
    // 获取错位字段集合
    List<FieldError> fieldErrors = result.getFieldErrors();
    // 获取本地locale,zh_CN
    Locale currentLocale = LocaleContextHolder.getLocale();
    for (FieldError fieldError : fieldErrors) {
        // 获取错误信息
        String errorMessage = messageSource.getMessage(fieldError, currentLocale);
        // 添加到错误消息集合内
        msg.append(fieldError.getField() + ":" + errorMessage + " ");
    }
    this.setCode(CODE_FAILED);
    this.setMsg(msg.toString());
    this.setData(null);
    return this;
}
 
Example #8
Source File: AbstractMessageSource.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Try to retrieve the given message from the parent {@code MessageSource}, if any.
 * @param code the code to lookup up, such as 'calculator.noRateSet'
 * @param args array of arguments that will be filled in for params
 * within the message
 * @param locale the locale in which to do the lookup
 * @return the resolved message, or {@code null} if not found
 * @see #getParentMessageSource()
 */
protected String getMessageFromParent(String code, Object[] args, Locale locale) {
	MessageSource parent = getParentMessageSource();
	if (parent != null) {
		if (parent instanceof AbstractMessageSource) {
			// Call internal method to avoid getting the default code back
			// in case of "useCodeAsDefaultMessage" being activated.
			return ((AbstractMessageSource) parent).getMessageInternal(code, args, locale);
		}
		else {
			// Check parent MessageSource, returning null if not found there.
			return parent.getMessage(code, args, null, locale);
		}
	}
	// Not found in parent either.
	return null;
}
 
Example #9
Source File: AbstractMessageSource.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Try to retrieve the given message from the parent {@code MessageSource}, if any.
 * @param code the code to lookup up, such as 'calculator.noRateSet'
 * @param args array of arguments that will be filled in for params
 * within the message
 * @param locale the locale in which to do the lookup
 * @return the resolved message, or {@code null} if not found
 * @see #getParentMessageSource()
 */
@Nullable
protected String getMessageFromParent(String code, @Nullable Object[] args, Locale locale) {
	MessageSource parent = getParentMessageSource();
	if (parent != null) {
		if (parent instanceof AbstractMessageSource) {
			// Call internal method to avoid getting the default code back
			// in case of "useCodeAsDefaultMessage" being activated.
			return ((AbstractMessageSource) parent).getMessageInternal(code, args, locale);
		}
		else {
			// Check parent MessageSource, returning null if not found there.
			// Covers custom MessageSource impls and DelegatingMessageSource.
			return parent.getMessage(code, args, null, locale);
		}
	}
	// Not found in parent either.
	return null;
}
 
Example #10
Source File: SummerXSLTView.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void setMessageSource(MessageSource messageSource) {
    this.messageSource = messageSource;
    if (this.messageSource instanceof ApplicationContext) {
        XsltConfiguration xsltConfiguration = ((ApplicationContext) this.messageSource).getBean(XsltConfiguration.class);
        if (xsltConfiguration != null) {
            mediaType = xsltConfiguration.getMediaType();
            devMode = xsltConfiguration.isDevMode();
            parameterPreffix = xsltConfiguration.getParameterPreffix();
            GenericKeyedObjectPoolConfig gop = new GenericKeyedObjectPoolConfig();
            gop.setMaxTotal(xsltConfiguration.getPoolsMaxPerKey() * XsltConfiguration.TOTAL_FACTOR);
            gop.setMinIdlePerKey((int) (xsltConfiguration.getPoolsMaxPerKey() / XsltConfiguration.MIN_IDLE_FACTOR));
            gop.setMaxIdlePerKey((int) (xsltConfiguration.getPoolsMaxPerKey() / XsltConfiguration.MAX_IDLE_FACTOR));
            gop.setMaxTotalPerKey(xsltConfiguration.getPoolsMaxPerKey());
            gop.setTestOnBorrow(false);
            gop.setMaxWaitMillis(10_000);
            log.info("Pool of unmarshallers initialised with concurrency {}", gop.getMaxTotalPerKey());
            marshallerPool = new GenericKeyedObjectPool<>(new MarshallerFactory(), gop);
        } else {
            throw new IllegalArgumentException("No XsltConfiguration bean found!");
        }
    }
}
 
Example #11
Source File: ResourceBundleThemeSource.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * This implementation returns a SimpleTheme instance, holding a
 * ResourceBundle-based MessageSource whose basename corresponds to
 * the given theme name (prefixed by the configured "basenamePrefix").
 * <p>SimpleTheme instances are cached per theme name. Use a reloadable
 * MessageSource if themes should reflect changes to the underlying files.
 * @see #setBasenamePrefix
 * @see #createMessageSource
 */
@Override
@Nullable
public Theme getTheme(String themeName) {
	Theme theme = this.themeCache.get(themeName);
	if (theme == null) {
		synchronized (this.themeCache) {
			theme = this.themeCache.get(themeName);
			if (theme == null) {
				String basename = this.basenamePrefix + themeName;
				MessageSource messageSource = createMessageSource(basename);
				theme = new SimpleTheme(themeName, messageSource);
				initParent(theme);
				this.themeCache.put(themeName, theme);
				if (logger.isDebugEnabled()) {
					logger.debug("Theme created: name '" + themeName + "', basename [" + basename + "]");
				}
			}
		}
	}
	return theme;
}
 
Example #12
Source File: ResourceBundleThemeSource.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * This implementation returns a SimpleTheme instance, holding a
 * ResourceBundle-based MessageSource whose basename corresponds to
 * the given theme name (prefixed by the configured "basenamePrefix").
 * <p>SimpleTheme instances are cached per theme name. Use a reloadable
 * MessageSource if themes should reflect changes to the underlying files.
 * @see #setBasenamePrefix
 * @see #createMessageSource
 */
@Override
@Nullable
public Theme getTheme(String themeName) {
	Theme theme = this.themeCache.get(themeName);
	if (theme == null) {
		synchronized (this.themeCache) {
			theme = this.themeCache.get(themeName);
			if (theme == null) {
				String basename = this.basenamePrefix + themeName;
				MessageSource messageSource = createMessageSource(basename);
				theme = new SimpleTheme(themeName, messageSource);
				initParent(theme);
				this.themeCache.put(themeName, theme);
				if (logger.isDebugEnabled()) {
					logger.debug("Theme created: name '" + themeName + "', basename [" + basename + "]");
				}
			}
		}
	}
	return theme;
}
 
Example #13
Source File: N2oMessagesConfiguration.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Bean("n2oMessageSource")
@ConditionalOnMissingBean(name = "n2oMessageSource")
public MessageSource n2oMessageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setDefaultEncoding(encoding.name());
    messageSource.setCacheSeconds(cacheSeconds);
    messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
            StringUtils.trimAllWhitespace(basename)));
    messageSource.addBasenames("n2o_messages", "n2o_content");
    return messageSource;
}
 
Example #14
Source File: ResourceBundleThemeSource.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a MessageSource for the given basename,
 * to be used as MessageSource for the corresponding theme.
 * <p>Default implementation creates a ResourceBundleMessageSource.
 * for the given basename. A subclass could create a specifically
 * configured ReloadableResourceBundleMessageSource, for example.
 * @param basename the basename to create a MessageSource for
 * @return the MessageSource
 * @see org.springframework.context.support.ResourceBundleMessageSource
 * @see org.springframework.context.support.ReloadableResourceBundleMessageSource
 */
protected MessageSource createMessageSource(String basename) {
	ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
	messageSource.setBasename(basename);
	if (this.defaultEncoding != null) {
		messageSource.setDefaultEncoding(this.defaultEncoding);
	}
	if (this.fallbackToSystemLocale != null) {
		messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
	}
	if (this.beanClassLoader != null) {
		messageSource.setBeanClassLoader(this.beanClassLoader);
	}
	return messageSource;
}
 
Example #15
Source File: ApplicationDslTests.java    From spring-fu with Apache License 2.0 5 votes vote down vote up
@Test
void createAnEmptyApplicationAndCheckMessageSource() {
	var app = application(a -> {});
	var context = app.run();
	assertFalse(context instanceof ReactiveWebServerApplicationContext);
	var messageSource = context.getBean(MessageSource.class);
	assertEquals("Spring Fu!", messageSource.getMessage("sample.message", null, Locale.getDefault()));
	context.close();
}
 
Example #16
Source File: ErrorsAutoConfigurationIT.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Bean
public WebErrorHandlers webErrorHandlers(MessageSource messageSource) {
    return WebErrorHandlers.builder(messageSource)
        .withErrorHandlers(new First())
        .withDefaultWebErrorHandler(new Sec())
        .build();
}
 
Example #17
Source File: TemplateAwareMessageSourceIT.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Bean
public MessageSource messageSource() {
    ResourceBundleMessageSource source = new ResourceBundleMessageSource();
    source.setBasename("templated_messages");

    return source;
}
 
Example #18
Source File: ErrorsMessageDemo.java    From geekbang-lessons with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        // 0. 创建 User 对象
        User user = new User();
        user.setName("小马哥");
        // 1. 选择 Errors - BeanPropertyBindingResult
        Errors errors = new BeanPropertyBindingResult(user, "user");
        // 2. 调用 reject 或 rejectValue
        // reject 生成 ObjectError
        // reject 生成 FieldError
        errors.reject("user.properties.not.null");
        // user.name = user.getName()
        errors.rejectValue("name", "name.required");

        // 3. 获取 Errors 中 ObjectError 和 FieldError
        // FieldError is ObjectError
        List<ObjectError> globalErrors = errors.getGlobalErrors();
        List<FieldError> fieldErrors = errors.getFieldErrors();
        List<ObjectError> allErrors = errors.getAllErrors();

        // 4. 通过 ObjectError 和 FieldError 中的 code 和 args 来关联 MessageSource 实现
        MessageSource messageSource = createMessageSource();

        for (ObjectError error : allErrors) {
            String message = messageSource.getMessage(error.getCode(), error.getArguments(), Locale.getDefault());
            System.out.println(message);
        }
    }
 
Example #19
Source File: WebErrorHandlersTest.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("deprecation")
@Parameters(method = "paramsForConstructor")
public void constructor_ShouldEnforceItsPreconditions(MessageSource messageSource,
                                                      List<WebErrorHandler> handlers,
                                                      Class<? extends Throwable> expectedException,
                                                      String expectedMessage) {
    assertThatThrownBy(() -> new WebErrorHandlers(messageSource, handlers, null, null, null))
        .isInstanceOf(expectedException)
        .hasMessage(expectedMessage);
}
 
Example #20
Source File: OutputFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Get the I18N description for this key. If the tool has supplied a messageService, then this is used to look up
    * the key and hence get the text. Otherwise if the tool has supplied a I18N languageFilename then it is accessed
    * via the shared toolActMessageService. If neither are supplied or the key is not found, then any "." in the name
    * are converted to space and this is used as the return value.
    *
    * This is normally used to get the description for a definition, in whic case the key should be in the format
    * output.desc.[definition name], key = definition name and addPrefix = true. For example a definition name of
    * "learner.mark" becomes output.desc.learner.mark.
    *
    * If you want to use this to get an arbitrary string from the I18N files, then set addPrefix = false and the
    * output.desc will not be added to the beginning.
    */
   protected String getI18NText(String key, boolean addPrefix) {
String translatedText = null;

MessageSource tmpMsgSource = getMsgSource();
if (tmpMsgSource != null) {
    if (addPrefix) {
	key = KEY_PREFIX + key;
    }
    Locale locale = LocaleContextHolder.getLocale();
    try {
	translatedText = tmpMsgSource.getMessage(key, null, locale);
    } catch (NoSuchMessageException e) {
	log.warn("Unable to internationalise the text for key " + key
		+ " as no matching key found in the msgSource");
    }
} else {
    log.warn("Unable to internationalise the text for key " + key
	    + " as no matching key found in the msgSource. The tool's OutputDefinition factory needs to set either (a) messageSource or (b) loadedMessageSourceService and languageFilename.");
}

if (translatedText == null || translatedText.length() == 0) {
    translatedText = key.replace('.', ' ');
}

return translatedText;
   }
 
Example #21
Source File: Service.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void setMessageSource(MessageSource messageSource) {
	if (this.messageSource != null) {
		throw new IllegalArgumentException("MessageSource should not be set twice");
	}
	this.messageSource = messageSource;
}
 
Example #22
Source File: MailService.java    From Full-Stack-Development-with-JHipster with MIT License 5 votes vote down vote up
public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender,
        MessageSource messageSource, SpringTemplateEngine templateEngine) {

    this.jHipsterProperties = jHipsterProperties;
    this.javaMailSender = javaMailSender;
    this.messageSource = messageSource;
    this.templateEngine = templateEngine;
}
 
Example #23
Source File: UtilConfig.java    From distributed-transaction-process with MIT License 5 votes vote down vote up
@Bean
public MethodInvokingFactoryBean methodInvokingFactoryBean(MessageSource source) {
    MethodInvokingFactoryBean bean = new MethodInvokingFactoryBean();
    bean.setTargetClass(CheckUtil.class);
    bean.setTargetMethod("setSource");
    bean.setArguments(new Object[]{ source });
    return bean;
}
 
Example #24
Source File: JstlUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Exposes JSTL-specific request attributes specifying locale
 * and resource bundle for JSTL's formatting and message tags,
 * using Spring's locale and MessageSource.
 * @param request the current HTTP request
 * @param messageSource the MessageSource to expose,
 * typically the current ApplicationContext (may be {@code null})
 * @see #exposeLocalizationContext(RequestContext)
 */
public static void exposeLocalizationContext(HttpServletRequest request, @Nullable MessageSource messageSource) {
	Locale jstlLocale = RequestContextUtils.getLocale(request);
	Config.set(request, Config.FMT_LOCALE, jstlLocale);
	TimeZone timeZone = RequestContextUtils.getTimeZone(request);
	if (timeZone != null) {
		Config.set(request, Config.FMT_TIME_ZONE, timeZone);
	}
	if (messageSource != null) {
		LocalizationContext jstlContext = new SpringLocalizationContext(messageSource, request);
		Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, jstlContext);
	}
}
 
Example #25
Source File: JstlUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Exposes JSTL-specific request attributes specifying locale
 * and resource bundle for JSTL's formatting and message tags,
 * using Spring's locale and MessageSource.
 * @param request the current HTTP request
 * @param messageSource the MessageSource to expose,
 * typically the current ApplicationContext (may be {@code null})
 * @see #exposeLocalizationContext(RequestContext)
 */
public static void exposeLocalizationContext(HttpServletRequest request, MessageSource messageSource) {
	Locale jstlLocale = RequestContextUtils.getLocale(request);
	Config.set(request, Config.FMT_LOCALE, jstlLocale);
	TimeZone timeZone = RequestContextUtils.getTimeZone(request);
	if (timeZone != null) {
		Config.set(request, Config.FMT_TIME_ZONE, timeZone);
	}
	if (messageSource != null) {
		LocalizationContext jstlContext = new SpringLocalizationContext(messageSource, request);
		Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, jstlContext);
	}
}
 
Example #26
Source File: ClassPathXmlApplicationContextTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testMessageSourceAware() {
	ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(CONTEXT_WILDCARD);
	MessageSource messageSource = (MessageSource) ctx.getBean("messageSource");
	Service service1 = (Service) ctx.getBean("service");
	assertEquals(ctx, service1.getMessageSource());
	Service service2 = (Service) ctx.getBean("service2");
	assertEquals(ctx, service2.getMessageSource());
	AutowiredService autowiredService1 = (AutowiredService) ctx.getBean("autowiredService");
	assertEquals(messageSource, autowiredService1.getMessageSource());
	AutowiredService autowiredService2 = (AutowiredService) ctx.getBean("autowiredService2");
	assertEquals(messageSource, autowiredService2.getMessageSource());
	ctx.close();
}
 
Example #27
Source File: SimpleTheme.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a SimpleTheme.
 * @param name the name of the theme
 * @param messageSource the MessageSource that resolves theme messages
 */
public SimpleTheme(String name, MessageSource messageSource) {
	Assert.notNull(name, "Name must not be null");
	Assert.notNull(messageSource, "MessageSource must not be null");
	this.name = name;
	this.messageSource = messageSource;
}
 
Example #28
Source File: JstlUtils.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Exposes JSTL-specific request attributes specifying locale
 * and resource bundle for JSTL's formatting and message tags,
 * using Spring's locale and MessageSource.
 * @param requestContext the context for the current HTTP request,
 * including the ApplicationContext to expose as MessageSource
 */
public static void exposeLocalizationContext(RequestContext requestContext) {
	Config.set(requestContext.getRequest(), Config.FMT_LOCALE, requestContext.getLocale());
	TimeZone timeZone = requestContext.getTimeZone();
	if (timeZone != null) {
		Config.set(requestContext.getRequest(), Config.FMT_TIME_ZONE, timeZone);
	}
	MessageSource messageSource = getJstlAwareMessageSource(
			requestContext.getServletContext(), requestContext.getMessageSource());
	LocalizationContext jstlContext = new SpringLocalizationContext(messageSource, requestContext.getRequest());
	Config.set(requestContext.getRequest(), Config.FMT_LOCALIZATION_CONTEXT, jstlContext);
}
 
Example #29
Source File: ResourceBundleThemeSource.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a MessageSource for the given basename,
 * to be used as MessageSource for the corresponding theme.
 * <p>Default implementation creates a ResourceBundleMessageSource.
 * for the given basename. A subclass could create a specifically
 * configured ReloadableResourceBundleMessageSource, for example.
 * @param basename the basename to create a MessageSource for
 * @return the MessageSource
 * @see org.springframework.context.support.ResourceBundleMessageSource
 * @see org.springframework.context.support.ReloadableResourceBundleMessageSource
 */
protected MessageSource createMessageSource(String basename) {
	ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
	messageSource.setBasename(basename);
	if (this.defaultEncoding != null) {
		messageSource.setDefaultEncoding(this.defaultEncoding);
	}
	if (this.fallbackToSystemLocale != null) {
		messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
	}
	if (this.beanClassLoader != null) {
		messageSource.setBeanClassLoader(this.beanClassLoader);
	}
	return messageSource;
}
 
Example #30
Source File: ClassPathBeanDefinitionScannerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testBeanAutowiredWithAnnotationConfigEnabled() {
	GenericApplicationContext context = new GenericApplicationContext();
	context.registerBeanDefinition("myBf", new RootBeanDefinition(StaticListableBeanFactory.class));
	ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
	scanner.setBeanNameGenerator(new TestBeanNameGenerator());
	int beanCount = scanner.scan(BASE_PACKAGE);
	assertEquals(12, beanCount);
	context.refresh();

	FooServiceImpl fooService = context.getBean("fooService", FooServiceImpl.class);
	StaticListableBeanFactory myBf = (StaticListableBeanFactory) context.getBean("myBf");
	MessageSource ms = (MessageSource) context.getBean("messageSource");
	assertTrue(fooService.isInitCalled());
	assertEquals("bar", fooService.foo(123));
	assertEquals("bar", fooService.lookupFoo(123));
	assertSame(context.getDefaultListableBeanFactory(), fooService.beanFactory);
	assertEquals(2, fooService.listableBeanFactory.size());
	assertSame(context.getDefaultListableBeanFactory(), fooService.listableBeanFactory.get(0));
	assertSame(myBf, fooService.listableBeanFactory.get(1));
	assertSame(context, fooService.resourceLoader);
	assertSame(context, fooService.resourcePatternResolver);
	assertSame(context, fooService.eventPublisher);
	assertSame(ms, fooService.messageSource);
	assertSame(context, fooService.context);
	assertEquals(1, fooService.configurableContext.length);
	assertSame(context, fooService.configurableContext[0]);
	assertSame(context, fooService.genericContext);
}