GVKun编程网logo

java.beans.beancontext.BeanContextProxy的实例源码(bean java)

19

在本文中,您将会了解到关于java.beans.beancontext.BeanContextProxy的实例源码的新资讯,同时我们还将为您解释beanjava的相关在本文中,我们将带你探索java.

在本文中,您将会了解到关于java.beans.beancontext.BeanContextProxy的实例源码的新资讯,同时我们还将为您解释bean java的相关在本文中,我们将带你探索java.beans.beancontext.BeanContextProxy的实例源码的奥秘,分析bean java的特点,并给出一些关于ApplicationContext注入Bean(多线程中注入Bean)、Bean context must contain FilterChainProxy、bean实例化的三种方式 bean标签常用属性 单例模式和多例模式的对象 BeanFactory和ApplicationContext:、com.itextpdf.text.RectangleReadOnly的实例源码的实用技巧。

本文目录一览:

java.beans.beancontext.BeanContextProxy的实例源码(bean java)

java.beans.beancontext.BeanContextProxy的实例源码(bean java)

项目:incubator-netbeans    文件:SerialDatanode.java   
private static Children getChildren(DataObject dobj,boolean noBeanInfo) {
    if (noBeanInfo) {
        return Children.LEAF;
    }
    InstanceCookie inst = (InstanceCookie)dobj.getCookie(InstanceCookie.class);
    if (inst == null) return Children.LEAF;
    try {
        Class clazz = inst.instanceClass();
        if (BeanContext.class.isAssignableFrom(clazz) ||
            BeanContextProxy.class.isAssignableFrom(clazz)) {
            return new InstanceChildren ();
        } else {
            return Children.LEAF;
        }
    } catch (Exception ex) {
        return Children.LEAF;
    }
}
项目:incubator-netbeans    文件:SerialDatanode.java   
private void init() {
    try {
        InstanceCookie ic = (InstanceCookie) dobj.getCookie(InstanceCookie.class);
        if (ic == null) {
            bean = null;
            return;
        }
        Class clazz = ic.instanceClass();
        if (BeanContext.class.isAssignableFrom(clazz)) {
            bean = ic.instanceCreate();
        } else if (BeanContextProxy.class.isAssignableFrom(clazz)) {
            bean = ((BeanContextProxy) ic.instanceCreate()).getBeanContextProxy();
        } else {
            bean = null;
        }
    } catch (Exception ex) {
        bean = null;
        Exceptions.printstacktrace(ex);
    }
    if (bean != null) {
        // attaches a listener to the bean
        ((BeanContext) bean).addBeanContextMembershipListener (contextL);
    }
    updateKeys();
}
项目:cn1    文件:BeanContextSupportTest.java   
public void testGetChildBeanContextChild_BeanContextChild() {
    MockBeanContextChild child = new MockBeanContextChild();
    BeanContextChild result = MockBeanContextSupport
            .publicGetChildBeanContextChild(child);
    assertSame(child,result);

    // Regression for HARMONY-1393
    class TestBeanException extends BeanContextChildSupport implements
            BeanContextProxy {
        private static final long serialVersionUID = -8544245159647566063L;
        private final BeanContextChildSupport childSupport = new BeanContextChildSupport();

        public BeanContextChild getBeanContextProxy() {
            return childSupport;
        }
    }
    TestBeanException bean = new TestBeanException();
    try {
        MockBeanContextSupport.publicGetChildBeanContextChild(bean);
        fail("IllegalArgumentException expected");
    } catch (IllegalArgumentException e) {
        // expected
    }
}
项目:studio    文件:InstanceNode.java   
private static Children getChildren(DataObject dobj,boolean noBeanInfo) {
    if (noBeanInfo) {
        return Children.LEAF;
    }
    InstanceCookie inst = (InstanceCookie)dobj.getCookie(InstanceCookie.class);
    if (inst == null) return Children.LEAF;
    try {
        Class clazz = inst.instanceClass();
        if (BeanContext.class.isAssignableFrom(clazz) ||
            BeanContextProxy.class.isAssignableFrom(clazz)) {
            return new InstanceChildren ((InstanceDataObject) dobj);
        } else {
            return Children.LEAF;
        }
    } catch (Exception ex) {
        return Children.LEAF;
    }
}
项目:freeVM    文件:BeanContextSupportTest.java   
public void testGetChildBeanContextChild_BeanContextChild() {
    MockBeanContextChild child = new MockBeanContextChild();
    BeanContextChild result = MockBeanContextSupport
            .publicGetChildBeanContextChild(child);
    assertSame(child,result);

    // Regression for HARMONY-1393
    class TestBeanException extends BeanContextChildSupport implements
            BeanContextProxy {
        private static final long serialVersionUID = -8544245159647566063L;
        private final BeanContextChildSupport childSupport = new BeanContextChildSupport();

        public BeanContextChild getBeanContextProxy() {
            return childSupport;
        }
    }
    TestBeanException bean = new TestBeanException();
    try {
        MockBeanContextSupport.publicGetChildBeanContextChild(bean);
        fail("IllegalArgumentException expected");
    } catch (IllegalArgumentException e) {
        // expected
    }
}
项目:incubator-netbeans    文件:BeanNode.java   
private static Children getChildren(Object bean) {
    if (bean instanceof BeanContext) {
        return new BeanChildren((BeanContext) bean);
    }

    if (bean instanceof BeanContextProxy) {
        BeanContextChild bch = ((BeanContextProxy) bean).getBeanContextProxy();

        if (bch instanceof BeanContext) {
            return new BeanChildren((BeanContext) bch);
        }
    }

    return Children.LEAF;
}
项目:incubator-netbeans    文件:SerialDatanode.java   
private static Children getChildren (Object bean,SerialDatanode task) {
    if (bean instanceof BeanContext)
        return new BeanChildren ((BeanContext)bean,new beanfactoryImpl(task));
    if (bean instanceof BeanContextProxy) {
        java.beans.beancontext.BeanContextChild bch = ((BeanContextProxy)bean).getBeanContextProxy();
        if (bch instanceof BeanContext)
            return new BeanChildren ((BeanContext)bch,new beanfactoryImpl(task));
    }
    return Children.LEAF;
}
项目:cn1    文件:BeanContextSupportTest.java   
public void testAdd_BCP() {
    MockBeanContextSupport support = new MockBeanContextSupport();
    support.waitOnChildInHooks = false;
    MockBeanContextMembershipListener l1 = new MockBeanContextMembershipListener();
    MockPropertychangelistener l2 = new MockPropertychangelistener();
    MockVetoablechangelistener l3 = new MockVetoablechangelistener();
    support.addBeanContextMembershipListener(l1);
    support.addPropertychangelistener("children",l2);
    support.addVetoablechangelistener("children",l3);

    BeanContextChild childPeer = new MockBeanContextChild();
    BeanContextProxy child = new MockBeanContextProxy(childPeer);
    support.add(child);
    support.records.assertRecord("initialize",null);
    support.records.assertRecord("validatePendingAdd",child,Boolean.TRUE);
    support.records.assertRecord("createBCSChild",childPeer,support.children().get(child));
    support.records.assertRecord("createBCSChild",support.children().get(childPeer));
    support.records.assertRecord("childJustAddedHook",support
            .children().get(child),null);
    support.records.assertRecord("childJustAddedHook",support
            .children().get(childPeer),null);
    support.records.assertEndOfRecords();
    assertTrue(l1.lastEventAdd);
    assertMembershipEvent(l1.lastEvent,support,null,Arrays
            .asList(new Object[] { child,childPeer }));
    assertNull(l2.lastEvent);
    assertNull(l3.lastEvent);

    assertSame(support,childPeer.getBeanContext());
    assertEquals(2,support.size());
}
项目:cn1    文件:BeanContextSupportTest.java   
public void testSize() {
    @SuppressWarnings("serial")
    class TestBean extends Component implements BeanContextProxy {
        public BeanContextChildSupport childSupport = new BeanContextChildSupport();

        public BeanContextChild getBeanContextProxy() {
            return childSupport;
        }
    }

    // Regression test for HARMONY-1829
    BeanContextSupport obj = new BeanContextSupport();
    obj.add(new TestBean());
    assertEquals(2,obj.size());
}
项目:studio    文件:BeanNode.java   
private static Children getChildren (Object bean) {
    if (bean instanceof BeanContext)
        return new BeanChildren ((BeanContext)bean);
    if (bean instanceof BeanContextProxy) {
        BeanContextChild bch = ((BeanContextProxy)bean).getBeanContextProxy();
        if (bch instanceof BeanContext)
            return new BeanChildren ((BeanContext)bch);
    }
    return Children.LEAF;
}
项目:studio    文件:InstanceNode.java   
public void propertyChange(PropertyChangeEvent evt) {
    if (evt != null && !evt.getPropertyName().equals(InstanceDataObject.PROP_COOKIE)) return;

    if (contextL != null && bean != null)
        ((BeanContext) bean).removeBeanContextMembershipListener (contextL);

    try {
        InstanceCookie ic = (InstanceCookie) dobj.getCookie(InstanceCookie.class);
        if (ic == null) {
            bean = null;
            return;
        }
        Class clazz = ic.instanceClass();
        if (BeanContext.class.isAssignableFrom(clazz)) {
            bean = ic.instanceCreate();
        } else if (BeanContextProxy.class.isAssignableFrom(clazz)) {
            bean = ((BeanContextProxy) dobj.instanceCreate()).getBeanContextProxy();
        } else {
            bean = null;
        }
    } catch (Exception ex) {
        bean = null;
        ErrorManager.getDefault().notify(ex);
    }
    if (bean != null) {
        // attaches a listener to the bean
        ((BeanContext) bean).addBeanContextMembershipListener (contextL);
    }
    updateKeys();
}
项目:studio    文件:InstanceNode.java   
private static Children getChildren (Object bean,InstanceDataObject task) {
    if (bean instanceof BeanContext)
        return new BeanChildren ((BeanContext)bean,new beanfactoryImpl(task));
    }
    return Children.LEAF;
}
项目:freeVM    文件:BeanContextSupportTest.java   
public void testAdd_BCP() {
    MockBeanContextSupport support = new MockBeanContextSupport();
    support.waitOnChildInHooks = false;
    MockBeanContextMembershipListener l1 = new MockBeanContextMembershipListener();
    MockPropertychangelistener l2 = new MockPropertychangelistener();
    MockVetoablechangelistener l3 = new MockVetoablechangelistener();
    support.addBeanContextMembershipListener(l1);
    support.addPropertychangelistener("children",support.size());
}
项目:freeVM    文件:BeanContextSupportTest.java   
public void testSize() {
    @SuppressWarnings("serial")
    class TestBean extends Component implements BeanContextProxy {
        public BeanContextChildSupport childSupport = new BeanContextChildSupport();

        public BeanContextChild getBeanContextProxy() {
            return childSupport;
        }
    }

    // Regression test for HARMONY-1829
    BeanContextSupport obj = new BeanContextSupport();
    obj.add(new TestBean());
    assertEquals(2,obj.size());
}
项目:cn1    文件:BeanContextSupportTest.java   
public void testRemoveObject_BCP() {
    MockBeanContextSupport support = new MockBeanContextSupport();
    support.waitOnChildInHooks = false;
    MockBeanContextMembershipListener l1 = new MockBeanContextMembershipListener();
    support.addBeanContextMembershipListener(l1);

    BeanContextChild childPeer = new MockBeanContextChild();
    BeanContextProxy child = new MockBeanContextProxy(childPeer);
    support.add(child);
    support.records.assertRecord("initialize",childPeer }));
    support.records.clear();
    l1.clearLastEvent();

    Object bcsChild = support.children().get(child);
    Object bcsChildPeer = support.children().get(childPeer);
    support.remove(child);
    support.records.assertRecord("validatePendingRemove",Boolean.TRUE);
    support.records.assertRecord("childJustRemovedHook",bcsChild,null);
    support.records.assertRecord("childJustRemovedHook",bcsChildPeer,null);
    support.records.assertEndOfRecords();
    assertTrue(l1.lastEventRemove);
    assertMembershipEvent(l1.lastEvent,childPeer }));

    assertNull(childPeer.getBeanContext());
    assertEquals(0,support.size());
}
项目:cn1    文件:BeanContextSupportTest.java   
public void testRemoveObject_BCP2() {
    MockBeanContextSupport support = new MockBeanContextSupport();
    support.waitOnChildInHooks = false;
    MockBeanContextMembershipListener l1 = new MockBeanContextMembershipListener();
    support.addBeanContextMembershipListener(l1);

    BeanContextChild childPeer = new MockBeanContextChild();
    BeanContextProxy child = new MockBeanContextProxy(childPeer);
    support.add(child);
    support.records.assertRecord("initialize",childPeer }));
    support.records.clear();
    l1.clearLastEvent();

    Object bcsChild = support.children().get(child);
    Object bcsChildPeer = support.children().get(childPeer);
    support.remove(childPeer);
    support.records.assertRecord("validatePendingRemove",support.size());
}
项目:freeVM    文件:BeanContextSupportTest.java   
public void testRemoveObject_BCP() {
    MockBeanContextSupport support = new MockBeanContextSupport();
    support.waitOnChildInHooks = false;
    MockBeanContextMembershipListener l1 = new MockBeanContextMembershipListener();
    support.addBeanContextMembershipListener(l1);

    BeanContextChild childPeer = new MockBeanContextChild();
    BeanContextProxy child = new MockBeanContextProxy(childPeer);
    support.add(child);
    support.records.assertRecord("initialize",support.size());
}
项目:freeVM    文件:BeanContextSupportTest.java   
public void testRemoveObject_BCP2() {
    MockBeanContextSupport support = new MockBeanContextSupport();
    support.waitOnChildInHooks = false;
    MockBeanContextMembershipListener l1 = new MockBeanContextMembershipListener();
    support.addBeanContextMembershipListener(l1);

    BeanContextChild childPeer = new MockBeanContextChild();
    BeanContextProxy child = new MockBeanContextProxy(childPeer);
    support.add(child);
    support.records.assertRecord("initialize",support.size());
}

ApplicationContext注入Bean(多线程中注入Bean)

ApplicationContext注入Bean(多线程中注入Bean)

文章目录

  • 前言
  • 一、线程中注入Service层或Dao层
  • 总结

前言

通常我们用一下几种方式注入 :

1、@Autowired 是通过 byType 的方式去注入的, 使用该注解,要求接口只能有一个实现类。
2、@Resource 可以通过 byName 和 byType的方式注入, 默认先按 byName的方式进行匹配,如果匹配不到,再按 byType的方式进行匹配。
3、@Qualifier 注解可以按名称注入, 但是注意是 类名。


一、线程中注入Service层或Dao层

有些情况我们需要在工具类或在new一个线程之后,线程中注入Service层或Dao层,这时候用以上方法是注入不进去

用以下方法即可注入:

package com.java.base.config;
 
import java.lang.annotation.Annotation;
import java.util.Map;
 
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
/***
 * 
 * <p>Title: MyApplicationContext</p>  
 * <p>Description: ApplicationContextAware 通过它spring容器会自动把上下文环境对象调用ApplicationContextAware接口中的setApplicationContext方法。
 * 				         通过这个上下文环境对象得到spring容器中的Bean
 * 				         在我们写的工具类获取线程中不能直接通过Spring注入,这个时候就需要通过ApplicationContext获取Bean
 * </p>  
 * @author shy  
 */
@Service
public class MyApplicationContext implements ApplicationContextAware {
 
	private static ApplicationContext context;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		context = applicationContext;
	}
	
	public static <T> T getBean(final Class<T> requiredType) {
		return context.getBean(requiredType);
	}
 
	public static <T> T getBean(final String beanName) {
		@SuppressWarnings("unchecked")
		final T bean = (T) context.getBean(beanName);
		return bean;
	}
 
	public static <T> Map<String, T> getBeans(final Class<T> requiredType) {
		return context.getBeansOfType(requiredType);
	}
 
	public static Map<String, Object> getBeansWithAnnotation(final Class<? extends Annotation> annotationType) {
		return context.getBeansWithAnnotation(annotationType);
	}
 
}
private XXXrService xxxService = MyApplicationContext.getBean(XXXService.class);

总结

如果此篇文章有帮助到您, 希望打大佬们能关注点赞收藏评论支持一波,非常感谢大家!
如果有不对的地方请指正!!!

参考1

Bean context must contain FilterChainProxy

Bean context must contain FilterChainProxy

Bean context must contain at least one bean of type org.acegisecurity.util.FilterChainProxy

在使用使用 Acegi 实现多种用户登录时,出现如下问题:
自己明明实现了该代理,可就是启动出错。
信息: Initializing Spring root WebApplicationContext
2009-03-29 10:10:37,894 INFO [org.springframework.web.context.ContextLoader] - <Root WebApplicationContext: initialization started>
2009-03-29 10:10:38,095 INFO [org.springframework.web.context.support.XmlWebApplicationContext] - <Refreshing org.springframework.web.context.support.XmlWebApplicationContext@55d93d: display name [Root WebApplicationContext]; startup date [Sun Mar 29 10:10:38 CST 2009]; root of context hierarchy>
2009-03-29 10:10:38,365 INFO [org.springframework.web.context.support.XmlWebApplicationContext] - <Bean factory for application context [org.springframework.web.context.support.XmlWebApplicationContext@55d93d]: org.springframework.beans.factory.support.DefaultListableBeanFactory@4ee70b>
2009-03-29 10:10:38,485 INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] - <Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4ee70b: defining beans []; root of factory hierarchy>
2009-03-29 10:10:38,485 INFO [org.springframework.web.context.ContextLoader] - <Root WebApplicationContext: initialization completed in 591 ms>
2009-3-29 10:10:38 org.apache.catalina.core.StandardContext filterStart
严重: Exception starting filter acegiFilterChain
javax.servlet.ServletException: Bean context must contain at least one bean of type org.acegisecurity.util.FilterChainProxy
at org.acegisecurity.util.FilterToBeanProxy.doInit(FilterToBeanProxy.java:145)
at org.acegisecurity.util.FilterToBeanProxy.init(FilterToBeanProxy.java:189)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:275)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:397)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:108)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3709)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4363)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:926)
at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:889)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1149)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
2009-3-29 10:10:38 org.apache.catalina.core.StandardContext start
严重: Error filterStart
2009-3-29 10:10:38 org.apache.catalina.core.StandardContext start
严重: Context [/Hotel] startup failed due to previous errors
2009-3-29 10:10:38 org.apache.catalina.core.ApplicationContext log
信息: Closing Spring root WebApplicationContext

问题找了很久,最后终于定位到了 web.xml 下,
<!--Spring ApplicationContext file path, separeted by comma.
    this parameter usring by Spring-Context loader-->
   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/hotel-*.xml</param-value>
    </context-param>

原来是 spring 的 xml 配置没读取到,改成如下就可以了:
<!--Spring ApplicationContext file path, separeted by comma.
    this parameter usring by Spring-Context loader-->
   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/hotel-*.xml,classpath*:hotel-*.xml</param-value>
    </context-param>

bean实例化的三种方式 bean标签常用属性 单例模式和多例模式的对象 BeanFactory和ApplicationContext:

bean实例化的三种方式 bean标签常用属性 单例模式和多例模式的对象 BeanFactory和ApplicationContext:

bean实例化的三种方式 bean标签常用属性 单例模式和多例模式的对象 beanfactory和ApplicationContext:

    • 学习网站/博客:
    • 1.bean实例化的三种方式:
    • 页面结构整体布局:
    • 运行结果如下:
    • 代码如下:
      • pom.xml:
      • Student:
      • MyStaticFactory :
      • MyInstanceFactory :
      • Test:
      • spring-1.xml:
    • 2.bean标签常用属性:
    • 代码整体布局:
    • 运行结果:
    • 添加/修改的代码如下:
      • spring-2.xml:(添加)
      • Student:(修改)
      • (test)Test2:
    • 3.单例模式和多例模式的对象:
    • 运行结果:
      • God:
      • Test:
      • (singleton)God:(添加)
      • (singleton)Test:(添加)
    • 4.BeanFactory和ApplicationContext:

学习网站/博客:

spring https://spring.io/

在这里插入图片描述


The loC Container https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans

在这里插入图片描述


Spring官方文档(中文版!!!) https://blog.csdn.net/li1376417539/article/details/104951358/

在这里插入图片描述

1.bean实例化的三种方式:

在这里插入图片描述


在这里插入图片描述


在这里插入图片描述

页面结构整体布局:

在这里插入图片描述

运行结果如下:

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

代码如下:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>lesson0820_spring</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <!--引入spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.18</version>
        </dependency>
    </dependencies>


</project>

Student:

package com.entity;

public class Student {

    public Student(){
        System.out.println("这是Student的构造方法...");
    }

    public void introduce(){
        System.out.println("我是一个学生");
    }
}

MyStaticFactory :

package com.factory;

import com.entity.Student;

/**
 * 静态工厂
 */
public class MyStaticFactory {
    /**
     * 静态返回学生实例
     * @return
     */
    public static Student createInstance(){
        System.out.println("调用静态工厂.....MyStaticFactory...createInstance");
        return new Student();
    }
}

MyInstanceFactory :

package com.factory;

import com.entity.Student;

/**
 * 实例工厂
 */
public class MyInstanceFactory {
    /**
     * 定义创建对象的实例方法
     * @return
     */
    public Student createInstance(){
        return new Student();
    }
}

Test:

package com.test;

import com.entity.Student;
import com.factory.MyInstanceFactory;
import com.factory.MyStaticFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClasspathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        //Student student = new Student();
        //创建spring bean容器对象
        ApplicationContext ac = new ClasspathXmlApplicationContext("spring-1.xml");
//        Student student = ac.getBean(Student.class);

        //静态工厂创建的对象,通过id名字,获取bean对象
//        Student s = (Student) ac.getBean("stu");
//        s.introduce();

        //实例工厂方式创建对象
        Student s2 = (Student) ac.getBean("stu2");
        s2.introduce();

    }
}

spring-1.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
        default-lazy-init="true"
        >

    <!--class属性必须配置,用于指明要创建的bean对象的类型
        lazy-init="true":延迟加载(懒汉模式)
        1.bean的方式定义对象
    -->
<!--    <beanlazy-init="true"/>-->

    <!--2.静态工厂方式创建学生对象-->
    <bean id="stu"factory-method="createInstance"/>

    <!--3.实例工厂创建对象-->
    <bean id="fac"/>
    <bean id="stu2" factory-bean="fac" factory-method="createInstance"/>

</beans>

在这里插入图片描述

2.bean标签常用属性:

在这里插入图片描述

代码整体布局:

在这里插入图片描述

运行结果:

在这里插入图片描述


在这里插入图片描述

在这里插入图片描述

添加/修改的代码如下:

spring-2.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
    >

    <!--
    class属性:用于指定要创建的bean对象的类型,必须写的属性
    id属性: 用于唯一标识该类型对象,不能重复,但是可以省略
    name属性: 可以认为是对bean对象起的别名,可以设置多个名字,用空格或逗号分隔。
             现在一般不用
    lazy-init:是否是延迟加载(懒汉,饿汉)。可以在beans中配置全局的延迟加载属性default-lazy-init
    scope:定义创建对象的方式和范围,singleton(单例),prototype(多例),request,session,global-session
          singleton(单例):表示容器中,只有一个对象,每次获取的都是同一个对象
          prototype(多例):每次都是new一个新的对象返回
    init-method:定义bean生命周期的初始化函数
    destroy-method:定义bean生命周期的销毁函数
    -->
    <bean id="stu"
          name="s1 s2"lazy-init="true"
          scope="prototype"
          init-method="initStu"
          destroy-method="destroyStu" />
</beans>

Student:(修改)

package com.entity;

import org.springframework.beans.factory.annotation.Autowired;

public class Student {

    public Student(){
        System.out.println("这是Student的构造方法...");
    }

    //自我介绍
    public void introduce(){
        System.out.println("我是一个学生");
    }

    //学生初始化
    public void initStu(){
        System.out.println("调用了学生的初始化方法");
    }

    //学生销毁
    public void destroyStu(){
        System.out.println("调用了学生的销毁方法");
    }
}

(test)Test2:

package com.test;

import com.entity.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClasspathXmlApplicationContext;

public class Test2 {
    public static void main(String[] args) {
        //创建spring容器
        ApplicationContext ctx = new ClasspathXmlApplicationContext("spring-2.xml");
        //根据id获取学生对象
        Student s1 =(Student) ctx.getBean("stu");
        System.out.println("s1:"+s1);
        //根据类型获取学生对象
        Student s2 = (Student) ctx.getBean(Student.class);
        System.out.println("s2:"+s2);
        //根据id和类型获取学生对象
        Student s3 = ctx.getBean("stu",Student.class);
        System.out.println("s3:"+s3);
        //根据name属性获取学生对象
        Student s4 = (Student) ctx.getBean("s1");
        Student s5 = (Student) ctx.getBean("s2");
        System.out.println("s4:"+s4);
        System.out.println("s5:"+s5);

    }
}

3.单例模式和多例模式的对象:

在这里插入图片描述

运行结果:

在这里插入图片描述

在这里插入图片描述

God:

package com.singleton;

public class God {

    public void createWorld(){
        System.out.println("上帝创造了世界....");
    }
}

Test:

package com.singleton;

public class Test {
    public static void main(String[] args) {
        God god = new God();
        god.createWorld();
        System.out.println(god);

        God god2 = new God();
        god2.createWorld();
        System.out.println(god2);
    }
}

(singleton)God:(添加)

package com.singleton;

public class God {

    //3.定义静态私有对象
    private static God god;

    //1.构造私有化
    private God(){

    }

    //2.定义静态工厂获取实例的方法,用于获取对象
    public static God createInstance(){
        if (god==null){
            god = new God();
        }
        return god;
    }

    public void createWorld(){
        System.out.println("上帝创造了世界....");
    }
}

(singleton)Test:(添加)

package com.singleton;

public class Test {
    public static void main(String[] args) {
        God god = God.createInstance();
        god.createWorld();
        System.out.println(god);

        God god2 = God.createInstance();
        god2.createWorld();
        System.out.println(god2);

    }
}

4.beanfactory和ApplicationContext:

在这里插入图片描述


在这里插入图片描述

在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


在这里插入图片描述

// A code block
var foo = 'bar';

// A code block
var foo = 'bar';

// A code block
var foo = 'bar';

// A code block
var foo = 'bar';

// A code block
var foo = 'bar';

// A code block
var foo = 'bar';

// A code block
var foo = 'bar';

// A code block
var foo = 'bar';

// A code block
var foo = 'bar';

com.itextpdf.text.RectangleReadOnly的实例源码

com.itextpdf.text.RectangleReadOnly的实例源码

项目:testarea-itext5    文件:VeryDenseMerging.java   
/**
 * <a href="http://stackoverflow.com/questions/28991291/how-to-remove-whitespace-on-merge">
 * How To Remove Whitespace on Merge
 * </a>
 * <p>
 * Testing {@link PdfVeryDenseMergetool} using the OP's files on a even smaller page.
 * </p>
 */
@Test
public void testMergeGrandizerFilesA5() throws DocumentException,IOException
{
    try (   InputStream docA = getClass().getResourceAsstream("Header.pdf");
            InputStream docB = getClass().getResourceAsstream("Body.pdf");
            InputStream docC = getClass().getResourceAsstream("Footer.pdf");    )
    {
        PdfVeryDenseMergetool tool = new PdfVeryDenseMergetool(new RectangleReadOnly(595,421),18,5);
        PdfReader readerA = new PdfReader(docA);
        PdfReader readerB = new PdfReader(docB);
        PdfReader readerC = new PdfReader(docC);
        try (FileOutputStream fos = new FileOutputStream(new File(RESULT_FOLDER,"GrandizerMerge-veryDense-A5.pdf")))
        {
            List<PdfReader> inputs = Arrays.asList(readerA,readerB,readerC);
            tool.merge(fos,inputs);
        }
        finally
        {
            readerA.close();
            readerB.close();
            readerC.close();
        }
    }
}
项目:carina    文件:AbstractPage.java   
public String savePageAsPdf(boolean scaled) throws IOException,DocumentException
{
    String pdfName = "";

    // Define test screenshot root
    String test = "";
    if (TestNamingUtil.isTestNameRegistered()) {
        test = TestNamingUtil.getTestNameByThread();
    } else {
        test = "undefined";
    }

    File testRootDir = ReportContext.getTestDir();
    File artifactsFolder = ReportContext.getArtifactsFolder();

    String fileID = test.replaceAll("\\W+","_") + "-" + System.currentTimeMillis();
    pdfName = fileID + ".pdf";

    String fullPdfPath = artifactsFolder.getAbsolutePath() + "/" + pdfName;
    // Todo: test this implementation and change back to capture if necessary
    Image image = Image.getInstance(testRootDir.getAbsolutePath() + "/" + Screenshot.captureFailure(driver,""));
    Document document = null;
    if (scaled)
    {
        document = new Document(PageSize.A4,10,10);
        if (image.getHeight() > (document.getPageSize().getHeight() - 20)
                || image.getScaledWidth() > (document.getPageSize().getWidth() - 20))
        {
            image.scaletoFit(document.getPageSize().getWidth() - 20,document.getPageSize().getHeight() - 20);
        }
    } else
    {
        document = new Document(new RectangleReadOnly(image.getScaledWidth(),image.getScaledHeight()));
    }
    PdfWriter.getInstance(document,new FileOutputStream(fullPdfPath));
    document.open();
    document.add(image);
    document.close();
    return fullPdfPath;
}
项目:testarea-itext5    文件:StampHeader.java   
byte[] createSampleDocument() throws IOException,DocumentException
{
    try (   ByteArrayOutputStream baos = new ByteArrayOutputStream()    )
    {
        Document doc = new Document(new RectangleReadOnly(842,595));
        PdfWriter.getInstance(doc,baos);
        doc.open();
        doc.add(new Paragraph("Test Page 1"));
        doc.newPage();
        doc.add(new Paragraph("Test Page 2"));
        doc.close();
        return baos.toByteArray();
    }
}

关于java.beans.beancontext.BeanContextProxy的实例源码bean java的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于ApplicationContext注入Bean(多线程中注入Bean)、Bean context must contain FilterChainProxy、bean实例化的三种方式 bean标签常用属性 单例模式和多例模式的对象 BeanFactory和ApplicationContext:、com.itextpdf.text.RectangleReadOnly的实例源码等相关内容,可以在本站寻找。

本文标签: