Spring

ApplicationContext

 

FileSystemXmlApplicationContext:提供XML文件的完整路径

 

ClassPathXmlApplicationContext容器会从 CLASSPATH 中搜索 bean 配置文件。

 

WebXmlApplicationContext:该容器会在一个 web 应用程序的范围内加载在 XML 文件中已被定义的 bean

 

Bean 的作用域:

singleton:单例(默认)

<bean id="..." class="..." scope="singleton">

</bean>

prototype:任意数量

 

Bean 的生命周期:

public void init() {

System.out.println("Bean is going through init.");

}

 

public void destroy() {

System.out.println("Bean will destroy now.");

}

----

   <bean id="news" class="com.huawei.TestMavenProj.spring.News"

                   init-method="init" destroy-method="destroy">

       <property name="title" value="Hello World!"/>

   </bean>

<beans default-init-method="init" default-destroy-method="destroy">

----

AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

News objA = (News) context.getBean("news");

System.out.println(objA.getTitle());

context.registerShutdownHook();

 

Bean 后置处理器(在初始化之前和之后调用):

public class InitHelloWorld implements BeanPostProcessor {

   public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

      System.out.println("BeforeInitialization : " + beanName);

      return bean;  // you can return any other object as well

   }

   public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

      System.out.println("AfterInitialization : " + beanName);

      return bean;  // you can return any other object as well

   }

}

 

Bean 定义模板和继承:

   <bean id="beanTeamplate" abstract="true">

      <property name="message1" value="Hello World!"/>

      <property name="message2" value="Hello Second World!"/>

      <property name="message3" value="Namaste India!"/>

   </bean>

 

   <bean id="helloIndia" class="com.tutorialspoint.HelloIndia" parent="beanTeamplate">

      <property name="message1" value="Hello India!"/>

      <property name="message3" value="Namaste India!"/>

   </bean>

posted @ 2018-04-19 19:54  AaronCnblogs  阅读(69)  评论(0)    收藏  举报