您的位置:首页 > 编程语言 > Java开发

Spring基本学习笔记

2014-10-06 11:55 148 查看
学习内容来源:http://www.tutorialspoint.com/spring/index.htm

1、安装Spring类库

2、配置Beans.xml

3、Bean Scopes 
默认 singleton (default)
prototype
request
session
global-session

4、Bean生命周期
1)Initialization 初始化
public class ExampleBean implements InitializingBean {

    public void afterPropertiesSet() {

      // do some initialization work

    }

   }

   基于xml配置 init-method

   <bean id="exampleBean" 

         class="examples.ExampleBean" init-method="init"/>
类的定义:
public class ExampleBean {

    public void init() {

      // do some initialization work

     }

   }

   2)Destruction 销毁

   public class ExampleBean implements DisposableBean {

   public void destroy() {

      // do some destruction work
}
}
基于xml配置 destroy-method
<bean id="exampleBean" 

         class="examples.ExampleBean" destroy-method="destroy"/>
类的定义:
public class ExampleBean {

    public void destroy() {

      // do some destruction work
}
}
It is recommended that you do not use the InitializingBean or DisposableBean callbacks, because XML configuration gives much flexibility in terms of naming your method.
calls the relevant destroy methods on your singleton beans so that all resources are released.

<?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-3.0.xsd">
   <bean id="helloWorld" 

       class="com.tutorialspoint.HelloWorld"

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

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

   </bean>
</beans>

5、Bean 后台处理
它会在调用init方法前执行
--------------------------------------------------
public void init() {
System.out.println("Bean is going through init.");
}

public void destroy() {
System.out.println("Bean will destroy now.");
}
----------------------------------------------------
public class InitHelloWorld implements BeanPostProcessor  {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName )
throws BeansException {
System.out.println("BeforeInitialization : " + beanName);
     return bean;  // you can return any other object as well
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("AfterInitialization : " + beanName);
     return bean;  // you can return any other object as well
}

}

6、Bean 继承定义
子类继承父类,override父类方法
Beans.xml------
  <bean id="helloWorld" class="com.turialpoint.HelloWorld">

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

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

   </bean>

   <bean id="helloIndia" class="com.turialpoint.HelloIndia"

       parent="helloWorld">

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

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

   </bean>

   MainApp--------------

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

HelloWorld objA = (HelloWorld) context.getBean("helloWorld");

objA.getMessage1();
objA.getMessage2();

HelloIndia objB = (HelloIndia) context.getBean("helloIndia");
objB.getMessage1();
objB.getMessage2();
objB.getMessage3();
------------------------

   显示结果:

   ---------------------------------------------------------------

   信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@8e96fc: defining beans [helloWorld,helloIndia]; root of factory hierarchy

World Message1 : Hello World!

World Message2 : Hello Second World!

India Message1 : Hello India!

India Message2 : Hello Second World!

India Message3 : Namaste India!

------------------------------------------------------------------------------

7、依赖注入
依赖注入类型与描述
1、基于构造器的依赖注入
<bean id="textEditor" class="com.turialpoint.TextEditor">

      <constructor-arg ref="spellChecker"></constructor-arg>

      </bean>
2、基于Setter依赖注入
<bean id="textEditor" class="com.tutorialspoint.TextEditor">

      <property name="spellChecker" ref="spellChecker"/>

   </bean>

8、注入集合
   <!-- Definition for javaCollection -->

   <bean id="javaCollection" class="com.turialpoint.JavaCollection">

      <!-- results in a setAddressList(java.util.List) call -->

      <property name="addressList">

        <list>

           <value>INDIA</value>

           <value>Pakistan</value>

           <value>USA</value>

           <value>USA</value>

        </list>

      </property>

     <!-- results in a setAddressSet(java.util.Set) call -->

     <property name="addressSet">

        <set>

           <value>INDIA</value>

           <value>Pakistan</value>

           <value>USA</value>

           <value>USA</value>

        </set>

      </property>

     <!-- results in a setAddressMap(java.util.Map) call -->

     <property name="addressMap">

        <map>

           <entry key="1" value="INDIA"/>

           <entry key="2" value="Pakistan"/>

           <entry key="3" value="USA"/>

           <entry key="4" value="USA"/>

        </map>

      </property>

     <!-- results in a setAddressProp(java.util.Properties) call -->

     <property name="addressProp">

        <props>

           <prop key="one">INDIA</prop>

           <prop key="two">Pakistan</prop>

           <prop key="three">USA</prop>

           <prop key="four">USA</prop>

        </props>

      </property>

   </bean>

9、Beans 自动装配

Mode Description

no This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter.

byName Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the
beans defined by the same names in the configuration file.

byType Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its
type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.
constructor
Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.

autodetect Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

10、基于配置的注解
1 @Required
The @Required annotation applies to bean property setter methods.
2 @Autowired
The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties.
3 @Qualifier
The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired.
4 JSR-250 Annotations
Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations.

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:context="http://www.springframework.org/schema/context"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
   <context:annotation-config/>

   <!-- bean definitions go here -->
</beans>

1、@Required  (applies to bean property setter methods)
     <!-- Definition for student bean -->

   <bean id="student" class="com.turialpoint.Student">

      <property name="name"  value="Zara" />

      <property name="age"  value="11" />

   </bean>

   

   Student.java

      private Integer age;
  private String name;

  @Required
  public void setAge(Integer age) {
     this.age = age;
  }
  public Integer getAge() {
     return age;
  }

  @Required
  public void setName(String name) {
     this.name = name;
  }
  public String getName() {
     return name;
  }

2、@Autowired

3、@Qualifier (名字相同)
<!-- Definition for profile bean -->

   <bean id="profile" class="com.tutorialspoint.Profile">

   </bean>

   <!-- Definition for student1 bean -->

   <bean id="student1" class="com.tutorialspoint.Student">

      <property name="name"  value="Zara" />

      <property name="age"  value="11"/>

   </bean>

   <!-- Definition for student2 bean -->

   <bean id="student2" class="com.tutorialspoint.Student">

      <property name="name"  value="Nuha" />

      <property name="age"  value="2"/>

   </bean>
————————————————————————————————————————————————————————————————
Profile.java
@Autowired
  @Qualifier("student1")
  private Student student;

  public Profile(){
     System.out.println("Inside Profile constructor." );
  }

  public void printAge() {
     System.out.println("Age : " + student.getAge() );
  }

  public void printName() {
     System.out.println("Name : " + student.getName() );
  }
  _________________________________________________________________
  Profile.java
   Profile profile = (Profile) context.getBean("profile");
     profile.printAge();
     profile.printName();

11、基于配置的java
package com.tutorialspoint;
import org.springframework.context.annotation.*;

@Configuration
public class AppConfig {

   @Bean

   public Foo foo() {

      return new Foo(bar());

   }

   @Bean

   public Bar bar() {

      return new Bar();
}
}
The @Import Annotation:
@Configuration

public class ConfigA {

   @Bean

   public A a() {

      return new A(); 

   }

}

@Configuration

@Import(ConfigA.class)

public class ConfigB {

   @Bean

   public B a() {

      return new A(); 

   }

}

public static void main(String[] args) {

   ApplicationContext ctx = 

   new AnnotationConfigApplicationContext(ConfigB.class);

   // now both beans A and B will be available...

   A a = ctx.getBean(A.class);

   B b = ctx.getBean(B.class);

}

public class Foo {

   public void init() {

      // initialization logic

   }

   public void cleanup() {

      // destruction logic

   }

}

@Configuration

public class AppConfig {

   @Bean(initMethod = "init", destroyMethod = "cleanup" )

   public Foo foo() {

      return new Foo();

   }

}

@Configuration

public class AppConfig {

   @Bean

   @Scope("prototype")

   public Foo foo() {

      return new Foo();

   }

}

12、在Spring中的事件处理
S.N. Spring Built-in Events & Description
1 ContextRefreshedEvent
This event is published when the ApplicationContext is either initialized or refreshed. This can also be raised using the refresh() method on the ConfigurableApplicationContext interface.
2 ContextStartedEvent
This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. You can poll your database or you can re/start any stopped application after receiving
this event.
3 ContextStoppedEvent
This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. You can do required housekeep work after receiving this event.
4 ContextClosedEvent
This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted.
5 RequestHandledEvent
This is a web-specific event telling all beans that an HTTP request has been serviced.

13、在Spring中定制事件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: