6. Use of Java disposed spring

A. Configuring spring Java-based way

  • We can not fully use Spring's xml way to configure, but all configured by the Java way!

  • JavaConfig is a sub-project of the Spring, after Spring4 become a core function

1. The entity class User.java

  • @Component:bean注入<bean id="user" class="ustc.wzh.pojo.User"></bean>

  • @Value ( "xxx"): the attribute value of the injected <property name = "name" value = "Wang" />

 1 //bean注入<bean id="user" class="ustc.wzh.pojo.User"></bean>
 2 @Component
 3 public class User {
 4 
 5     private String name;
 6 
 7     public String getName() {
 8         return name;
 9     }
10 
11     //属性值注入<property name="name" value="小王"/>
12     @Value("小王")
13     public void setName(String name) {
14         this.name = name;
15     }
16 
17     @Override
18     public String toString() {
19         return "User{" +
20                 "name='" + name + '\'' +
21                 '}';
22     }
23 }

2.Java configuration class

(1)appConfig.java:

  • @Configuration: When beans.xml configuration file in, register it with the container to the Spring-managed, it is itself a @Component

  • @ComponentScan ( "ustc.wzh.pojo"): Specifies the package to be scanned

  • @Import (appConfig2.class): import additional profile parameters for the Java class class object configuration file

. 1  // @Configuration beans.xml configuration file corresponds, to the vessel to be registered hosted Spring, which is itself a @Component 
2  @Configuration
 . 3 @ComponentScan ( "ustc.wzh.pojo" )
 . 4  // @Import with to import additional profiles 
. 5 @Import (appConfig2. class )
 . 6  public  class appconfig {
 . 7  
. 8      // registration of a bean, bean corresponds to a tag <bean id = "user" class = "ustc.wzh.pojo.User"> </ the bean>
 . 9      // method called id attribute value, the attribute value of the return type is class 
10      @Bean
 . 11      public the User User () {
 12 is          return  new new the User ();
 13 is      }
14 }

(2)appConfig2.java:

1 @Configuration
2 public class appConfig2 {
3 }

3. Test class

  • AnnotationConfigApplicationContext: entirely in Java way to configure Spring, we can only be obtained through the container AnnotationConfigApplicationContext, loaded by the class object configuration of class

. 1  public  class the MyTest {
 2  
. 3      public  static  void main (String [] args) {
 . 4  
. 5          // entirely in Java is arranged Spring, we can only obtain a container by AnnotationConfigApplicationContext, loaded by the class object class configuration 
. 6          the ApplicationContext context = new new AnnotationConfigApplicationContext (appconfig. class );
 . 7          the User User = (the User) context.getBean ( "User" );
 . 8  
. 9          System.out.println (user.getName ());
 10      }
 . 11 }

 

Guess you like

Origin www.cnblogs.com/zhihaospace/p/12324586.html