下面列出了怎么用org.springframework.beans.FatalBeanException的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
@SuppressWarnings("resource")
public void handlerBeanNotFound() {
MockServletContext sc = new MockServletContext("");
XmlWebApplicationContext root = new XmlWebApplicationContext();
root.setServletContext(sc);
root.setConfigLocations("/org/springframework/web/servlet/handler/map1.xml");
root.refresh();
XmlWebApplicationContext wac = new XmlWebApplicationContext();
wac.setParent(root);
wac.setServletContext(sc);
wac.setNamespace("map2err");
wac.setConfigLocations("/org/springframework/web/servlet/handler/map2err.xml");
try {
wac.refresh();
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (FatalBeanException ex) {
NoSuchBeanDefinitionException nestedEx = (NoSuchBeanDefinitionException) ex.getCause();
assertEquals("mainControlle", nestedEx.getBeanName());
}
}
private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) {
if (feature instanceof JsonParser.Feature) {
objectMapper.configure((JsonParser.Feature) feature, enabled);
}
else if (feature instanceof JsonGenerator.Feature) {
objectMapper.configure((JsonGenerator.Feature) feature, enabled);
}
else if (feature instanceof SerializationFeature) {
objectMapper.configure((SerializationFeature) feature, enabled);
}
else if (feature instanceof DeserializationFeature) {
objectMapper.configure((DeserializationFeature) feature, enabled);
}
else if (feature instanceof MapperFeature) {
objectMapper.configure((MapperFeature) feature, enabled);
}
else {
throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName());
}
}
@Override
@SuppressWarnings("unchecked")
public final Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
try {
Class<T> lClass = getLifeCycleInterface();
if (lClass.isInstance(bean)) {
// Check if the bean is registered in the context.
// If not it was created by the container and so there
// is no need to execute the callback.
if (factory.containsBeanDefinition(name)) {
executeLifecycleMethodBeforeInit((T) bean, name);
}
}
} catch (Exception e) {
throw new FatalBeanException("Unable to execute lifecycle method on bean" + name, e);
}
return bean;
}
private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) {
if (feature instanceof JsonParser.Feature) {
objectMapper.configure((JsonParser.Feature) feature, enabled);
}
else if (feature instanceof JsonGenerator.Feature) {
objectMapper.configure((JsonGenerator.Feature) feature, enabled);
}
else if (feature instanceof SerializationFeature) {
objectMapper.configure((SerializationFeature) feature, enabled);
}
else if (feature instanceof DeserializationFeature) {
objectMapper.configure((DeserializationFeature) feature, enabled);
}
else if (feature instanceof MapperFeature) {
objectMapper.configure((MapperFeature) feature, enabled);
}
else {
throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName());
}
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
ConfigurationProvider confProvider = beanFactory.getBean(ConfigurationProvider.class);
try {
HierarchicalConfiguration<ImmutableNode> config = confProvider.getConfiguration("quota");
String quotaRootResolver = config.configurationAt(QUOTA_ROOT_RESOLVER_BEAN).getString(PROVIDER, DEFAULT_IMPLEMENTATION);
String currentQuotaManager = config.configurationAt(CURRENT_QUOTA_MANAGER_BEAN).getString(PROVIDER, "none");
String maxQuotaManager = config.configurationAt(MAX_QUOTA_MANAGER).getString(PROVIDER, FAKE_IMPLEMENTATION);
String quotaManager = config.configurationAt(QUOTA_MANAGER_BEAN).getString(PROVIDER, FAKE_IMPLEMENTATION);
String quotaUpdater = config.configurationAt(UPDATES_BEAN).getString(PROVIDER, FAKE_IMPLEMENTATION);
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
registerAliasForQuotaRootResolver(quotaRootResolver, registry);
registerAliasForCurrentQuotaManager(currentQuotaManager, registry);
registerAliasForMaxQuotaManager(maxQuotaManager, registry);
registerAliasForQuotaManager(quotaManager, registry);
registerAliasForQuotaUpdater(quotaUpdater, registry);
} catch (ConfigurationException e) {
throw new FatalBeanException("Unable to configure Quota system", e);
}
}
private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) {
if (feature instanceof JsonParser.Feature) {
objectMapper.configure((JsonParser.Feature) feature, enabled);
}
else if (feature instanceof JsonGenerator.Feature) {
objectMapper.configure((JsonGenerator.Feature) feature, enabled);
}
else if (feature instanceof SerializationFeature) {
objectMapper.configure((SerializationFeature) feature, enabled);
}
else if (feature instanceof DeserializationFeature) {
objectMapper.configure((DeserializationFeature) feature, enabled);
}
else if (feature instanceof MapperFeature) {
objectMapper.configure((MapperFeature) feature, enabled);
}
else {
throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName());
}
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
AnnotatedTypeMetadata metadata) {
String prefix = (String) attribute(metadata, "prefix");
Class<?> value = (Class<?>) attribute(metadata, "value");
ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getEnvironment();
try {
new Binder(ConfigurationPropertySources.from(environment.getPropertySources()))
.bind(prefix, Bindable.of(value))
.orElseThrow(
() -> new FatalBeanException("Could not bind DataSourceSettings properties"));
return new ConditionOutcome(true, String.format("Map property [%s] is not empty", prefix));
} catch (Exception e) {
//ignore
}
return new ConditionOutcome(false, String.format("Map property [%s] is empty", prefix));
}
/**
* 复制Map属性
*
* @param source
* @param target
* @throws BeansException
*/
public static void copyProperties(Map source, Object target) throws BeansException {
Iterator<Map.Entry> s = source.entrySet().iterator();
//获取目标对象所有属性
PropertyDescriptor[] targetPds = getPropertyDescriptors(target.getClass());
for (PropertyDescriptor targetPd : targetPds) {
//获取目标对象属性写方法
Method writeMethod = targetPd.getWriteMethod();
if (null != writeMethod) {
try {
while (s.hasNext()) {
Map.Entry en = s.next();
if (en.getKey().equals(targetPd.getName())) {
//如果方法访问权限不足,设置方法允许访问权限
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, new Object[]{en.getValue()});
}
}
} catch (Throwable var15) {
throw new FatalBeanException("Could not copy property \'" + targetPd.getName() + "\' from source to target", var15);
}
}
}
}
/**
* 复制实体属性到map
*
* @param source
* @param target
* @throws BeansException
*/
public static void copyProperties(Object source, Map target) throws BeansException {
PropertyDescriptor[] sourcePds = getPropertyDescriptors(source.getClass());
for (PropertyDescriptor sourcePd :
sourcePds) {
Method readMethod = sourcePd.getReadMethod();
if (null != readMethod) {
try {
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
target.put(sourcePd.getName(), value);
} catch (Throwable ex) {
throw new FatalBeanException(
"Could not copy property '" + sourcePd.getName() + "' from source to target", ex);
}
}
}
}
public void executePostInitProcesses() throws BeansException {
SystemInstallationReport report = null;
try {
report = this.extractReport();
List<Component> components = this.getComponentManager().getCurrentComponents();
for (Component component : components) {
executeComponentPostInitProcesses(component, report);
}
} catch (Throwable t) {
logger.error("Error while executing post processes", t);
throw new FatalBeanException("Error while executing post processes", t);
} finally {
if (null != report && report.isUpdated()) {
this.saveReport(report);
}
}
}
@Test
public void handlerBeanNotFound() throws Exception {
MockServletContext sc = new MockServletContext("");
XmlWebApplicationContext root = new XmlWebApplicationContext();
root.setServletContext(sc);
root.setConfigLocations(new String[] {"/org/springframework/web/servlet/handler/map1.xml"});
root.refresh();
XmlWebApplicationContext wac = new XmlWebApplicationContext();
wac.setParent(root);
wac.setServletContext(sc);
wac.setNamespace("map2err");
wac.setConfigLocations(new String[] {"/org/springframework/web/servlet/handler/map2err.xml"});
try {
wac.refresh();
fail("Should have thrown NoSuchBeanDefinitionException");
}
catch (FatalBeanException ex) {
NoSuchBeanDefinitionException nestedEx = (NoSuchBeanDefinitionException) ex.getCause();
assertEquals("mainControlle", nestedEx.getBeanName());
}
}
private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) {
if (feature instanceof JsonParser.Feature) {
objectMapper.configure((JsonParser.Feature) feature, enabled);
}
else if (feature instanceof JsonGenerator.Feature) {
objectMapper.configure((JsonGenerator.Feature) feature, enabled);
}
else if (feature instanceof SerializationFeature) {
objectMapper.configure((SerializationFeature) feature, enabled);
}
else if (feature instanceof DeserializationFeature) {
objectMapper.configure((DeserializationFeature) feature, enabled);
}
else if (feature instanceof MapperFeature) {
objectMapper.configure((MapperFeature) feature, enabled);
}
else {
throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName());
}
}
@Override
public void release() throws FatalBeanException {
synchronized (bfgInstancesByKey) {
BeanFactory savedRef = this.groupContextRef;
if (savedRef != null) {
this.groupContextRef = null;
BeanFactoryGroup bfg = bfgInstancesByObj.get(savedRef);
if (bfg != null) {
bfg.refCount--;
if (bfg.refCount == 0) {
destroyDefinition(savedRef, resourceLocation);
bfgInstancesByKey.remove(resourceLocation);
bfgInstancesByObj.remove(savedRef);
}
}
else {
// This should be impossible.
logger.warn("Tried to release a SingletonBeanFactoryLocator group definition " +
"more times than it has actually been used. Resource name [" + resourceLocation + "]");
}
}
}
}
@Override
@SuppressWarnings("unchecked")
public final Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
try {
Class<T> lClass = getLifeCycleInterface();
if (lClass.isInstance(bean)) {
// Check if the bean is registered in the context.
// If not it was created by the container and so there is no
// need to execute the callback.
if (factory.containsBeanDefinition(name)) {
executeLifecycleMethodAfterInit((T) bean, name);
}
}
} catch (Exception e) {
throw new FatalBeanException("Unable to execute lifecycle method on bean" + name, e);
}
return bean;
}
public void afterSingletonsInstantiated() {
org.bytesoft.bytetcc.TransactionCoordinator transactionCoordinator = //
this.beanFactory.getBean(org.bytesoft.bytetcc.TransactionCoordinator.class);
org.bytesoft.bytetcc.supports.dubbo.CompensableBeanRegistry beanRegistry = //
this.beanFactory.getBean(org.bytesoft.bytetcc.supports.dubbo.CompensableBeanRegistry.class);
org.bytesoft.bytetcc.CompensableCoordinator compensableCoordinator = //
this.beanFactory.getBean(org.bytesoft.bytetcc.CompensableCoordinator.class);
if (compensableCoordinator == null) {
throw new FatalBeanException("No configuration of class org.bytesoft.bytetcc.CompensableCoordinator was found.");
} else if (transactionCoordinator == null) {
throw new FatalBeanException("No configuration of class org.bytesoft.bytetcc.TransactionCoordinator was found.");
} else if (beanRegistry == null) {
throw new FatalBeanException(
"No configuration of class org.bytesoft.bytetcc.supports.dubbo.CompensableBeanRegistry was found.");
}
this.initializeForProvider(transactionCoordinator);
}
public static void loadFromFile(Path filePath)
{
try( BufferedReader reader = new BufferedReader(new FileReader(filePath.toString()))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.length() > 0) {
String[] tokens = line.split(":", 3);
map.put(tokens[0], new RedisInstance(tokens[1], tokens[2]));
}
}
}
catch( IOException ex){
Logging.writeLine("Error while reading file %s", filePath);
Logging.logException(ex);
throw new FatalBeanException(ex.getMessage());
}
}
public static void LogError(Exception ex)
{
if (ex instanceof JedisConnectionException) {
Throwable cause = ex.getCause();
if (cause != null && cause instanceof SocketTimeoutException)
Logging.write("T");
else
Logging.write("C");
} else if (ex instanceof JedisBusyException) {
Logging.write("B");
} else if (ex instanceof JedisException) {
Logging.write("E");
} else if (ex instanceof IOException){
Logging.write("C");
} else {
Logging.logException(ex);
throw new FatalBeanException(ex.getMessage(), ex); // unexpected exception type, so abort test for investigation
}
}
private void registerAliasForQuotaManager(String quotaManager, BeanDefinitionRegistry registry) {
if (quotaManager.equalsIgnoreCase(FAKE_IMPLEMENTATION)) {
registry.registerAlias("noQuotaManager", QUOTA_MANAGER_BEAN);
} else if (quotaManager.equalsIgnoreCase("store")) {
registry.registerAlias("storeQuotaManager", QUOTA_MANAGER_BEAN);
} else {
throw new FatalBeanException("Unreadable value for Quota Manager : " + quotaManager);
}
}
public void saveReport(SystemInstallationReport report) throws BeansException {
if (null == report || report.getReports().isEmpty()) {
return;
}
try {
InstallationReportDAO dao = new InstallationReportDAO();
DataSource dataSource = (DataSource) this.getBeanFactory().getBean("portDataSource");
dao.setDataSource(dataSource);
dao.saveConfigItem(report.toXml(), this.getConfigVersion());
this.getCacheWrapper().setCurrentReport(report);
} catch (Throwable t) {
logger.error("Error saving report", t);
throw new FatalBeanException("Error saving report", t);
}
}
@Test
public void testNoSuchInitMethod() {
DefaultListableBeanFactory xbf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INITIALIZERS_CONTEXT);
try {
xbf.getBean("init-method3");
fail();
}
catch (FatalBeanException ex) {
// check message is helpful
assertTrue(ex.getMessage().contains("initializers.xml"));
assertTrue(ex.getMessage().contains("init-method3"));
assertTrue(ex.getMessage().contains("init"));
}
}
@Test
public void alwaysTrueForThrowable() {
RollbackRuleAttribute rr = new RollbackRuleAttribute(java.lang.Throwable.class.getName());
assertTrue(rr.getDepth(new MyRuntimeException("")) > 0);
assertTrue(rr.getDepth(new IOException()) > 0);
assertTrue(rr.getDepth(new FatalBeanException(null,null)) > 0);
assertTrue(rr.getDepth(new RuntimeException()) > 0);
}
/**
* Check that we fail gracefully if the user doesn't set any transaction attributes.
*/
@Test
public void testNoTransactionAttributeSource() {
try {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource("noTransactionAttributeSource.xml", getClass()));
bf.getBean("noTransactionAttributeSource");
fail("Should require TransactionAttributeSource to be set");
}
catch (FatalBeanException ex) {
// Ok
}
}
private Object getTargetObject(Object proxy) throws BeansException {
if (AopUtils.isJdkDynamicProxy(proxy)) {
try {
return ((Advised)proxy).getTargetSource().getTarget();
} catch (Exception e) {
throw new FatalBeanException("Error getting target of JDK proxy", e);
}
}
return proxy;
}
private Class<?> createStageClass( String beanName, String className ) {
try {
Class<?> aClass = Thread.currentThread().getContextClassLoader().loadClass( className );
return stageClassCreator.createStageClass( aClass );
} catch( ClassNotFoundException e ) {
throw new FatalBeanException( "Error while trying to create JGiven stage for bean " + beanName, e );
}
}
private void registerAliasForMaxQuotaManager(String maxQuotaManager, BeanDefinitionRegistry registry) {
if (maxQuotaManager.equalsIgnoreCase(FAKE_IMPLEMENTATION)) {
registry.registerAlias("noMaxQuotaManager", MAX_QUOTA_MANAGER);
} else if (maxQuotaManager.equalsIgnoreCase(IN_MEMORY_IMPLEMENTATION)) {
registry.registerAlias("inMemoryMaxQuotaManager", MAX_QUOTA_MANAGER);
} else if (maxQuotaManager.equalsIgnoreCase(JPA_IMPLEMENTATION)) {
registry.registerAlias("jpaMaxQuotaManager", MAX_QUOTA_MANAGER);
} else {
throw new FatalBeanException("Unreadable value for Max Quota Manager : " + maxQuotaManager);
}
}
private void registerAliasForQuotaUpdater(String quotaUpdater, BeanDefinitionRegistry registry) {
if (quotaUpdater.equalsIgnoreCase(EVENT)) {
registry.registerAlias("eventQuotaUpdater", QUOTA_UPDATER_BEAN);
} else if (quotaUpdater.equalsIgnoreCase(FAKE_IMPLEMENTATION)) {
registry.registerAlias("noQuotaUpdater", QUOTA_UPDATER_BEAN);
} else {
throw new FatalBeanException("Unreadable value for Quota Updater : " + quotaUpdater);
}
}
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor pd = new PropertyDescriptor("value", ValueBean.class);
pd.setPropertyEditorClass(MyNumberEditor.class);
return new PropertyDescriptor[] {pd};
}
catch (IntrospectionException ex) {
throw new FatalBeanException("Couldn't create PropertyDescriptor", ex);
}
}
@Test
public void testRequiresListableBeanFactoryAndChokesOnAnythingElse() throws Exception {
BeanFactory beanFactory = mock(BeanFactory.class);
try {
ServiceLocatorFactoryBean factory = new ServiceLocatorFactoryBean();
factory.setBeanFactory(beanFactory);
}
catch (FatalBeanException ex) {
// expected
}
}
private Object getTargetObject(Object proxy) throws BeansException {
if (AopUtils.isJdkDynamicProxy(proxy)) {
try {
return ((Advised)proxy).getTargetSource().getTarget();
} catch (Exception e) {
throw new FatalBeanException("Error getting target of JDK proxy", e);
}
}
return proxy;
}
@Test
public void testForRefreshedScriptHavingErrorPickedUpOnFirstCall() throws Exception {
BeanDefinition processorBeanDefinition = createScriptFactoryPostProcessor(true);
BeanDefinition scriptedBeanDefinition = createScriptedGroovyBean();
BeanDefinitionBuilder collaboratorBuilder = BeanDefinitionBuilder.rootBeanDefinition(DefaultMessengerService.class);
collaboratorBuilder.addPropertyReference(MESSENGER_BEAN_NAME, MESSENGER_BEAN_NAME);
GenericApplicationContext ctx = new GenericApplicationContext();
ctx.registerBeanDefinition(PROCESSOR_BEAN_NAME, processorBeanDefinition);
ctx.registerBeanDefinition(MESSENGER_BEAN_NAME, scriptedBeanDefinition);
final String collaboratorBeanName = "collaborator";
ctx.registerBeanDefinition(collaboratorBeanName, collaboratorBuilder.getBeanDefinition());
ctx.refresh();
Messenger messenger = (Messenger) ctx.getBean(MESSENGER_BEAN_NAME);
assertEquals(MESSAGE_TEXT, messenger.getMessage());
// cool; now let's change the script and check the refresh behaviour...
pauseToLetRefreshDelayKickIn(DEFAULT_SECONDS_TO_PAUSE);
StaticScriptSource source = getScriptSource(ctx);
// needs The Sundays compiler; must NOT throw any exception here...
source.setScript("I keep hoping you are the same as me, and I'll send you letters and come to your house for tea");
Messenger refreshedMessenger = (Messenger) ctx.getBean(MESSENGER_BEAN_NAME);
try {
refreshedMessenger.getMessage();
fail("Must have thrown an Exception (invalid script)");
}
catch (FatalBeanException expected) {
assertTrue(expected.contains(ScriptCompilationException.class));
}
}