Java tutorial
/* * Copyright 2010-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.reusables.test; import org.apache.commons.lang.Validate; import org.springframework.context.ApplicationContext; /** * Utilities for the Springframework when unit testing. * * @author marcel **/ public final class SpringTestUtils { private SpringTestUtils() { // Util class. } /** * Get a single bean form the context with the given type. * * @param <T> Type of the bean. * @param ctx The Spring context. * @param type Type of the bean. * @return The bean with the given type. */ public static <T> T getBeanByType(final ApplicationContext ctx, final Class<T> type) { final String[] names = ctx.getBeanNamesForType(type); Validate.isTrue(names.length == 1, "Number of beans of type '" + type.getName() + "' found: " + names.length); return (T) ctx.getBean(names[0]); } /** * Find a single bean form the context with the given type. * * @param <T> Type of the bean. * @param ctx The Spring context. * @param type Type of the bean. * @return The bean with the given type, or null if not exactly one bean of the given type was present. */ public static <T> T findBeanByType(final ApplicationContext ctx, final Class<T> type) { final String[] names = ctx.getBeanNamesForType(type); return names.length == 1 ? (T) ctx.getBean(names[0]) : null; } }