Java——Spring配置

by admin on 2019年10月7日

Chinese.java

<?xml version="1.0" encoding="UTF-8"?>
<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"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
 default-autowire="byName" default-lazy-init="true">
 <!--  default-autowire="byName" 根据属性名自动装配,default-lazy-init="true"  spring配置默认default-lazy-init为false,当配置为true时sping不会再去加载整个对象实例图,大大减少了初始化的时间,减少了spring的启动速度。
    这样做只是为了在开发过程中节约启动时间,在部署到实际环境中,倒是没必要设置default-lazy-init为true。毕竟部署到实际环境中不是经常的事,每次启动1分钟倒不是大问题,而且可以提高服务器效率 -->
 <!-- 配置数据源 -->
 <bean id="dataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName">
           <value>com.mysql.jdbc.Driver</value>
      </property>
      <property name="url">
           <value>jdbc:mysql://localhost/ssh?characterEncoding=utf-8</value>
      </property>
      <property name="username">
           <value>root</value>
      </property>
      <property name="password">
           <value>123</value>
      </property>
 </bean>

 <!--配置SessionFactory -->
 <bean id="sessionFactory"  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
      <property name="dataSource">
           <ref bean="dataSource" />
      </property>
      <property name="mappingResources">
           <list>
                <value>com/ssh/pojo/User.hbm.xml</value>
           </list>
     </property>
      <property name="hibernateProperties">
           <props>
                <prop key="hibernate.show_sql">true</prop>
           </props>
      </property>
 </bean>
 
 <!-- hibernateTemplate -->
 <bean id="hibernateTemplate"  class="org.springframework.orm.hibernate3.HibernateTemplate">
      <property name="sessionFactory">
           <ref bean="sessionFactory" />
      </property>
 </bean>

 <!-- 配置数据持久层 -->
 <bean id="userDao"  class="com.ssh.dao.impl.UserDaoImpl">
      <property name="hibernateTemplate" ref="hibernateTemplate"></property>
 </bean>
 
 <!-- 配置业务逻辑层 -->
 <bean id="userService"  class="com.ssh.service.impl.UserServiceImpl">
      <property name="userDao" ref="userDao"></property>
 </bean>
 
 <!-- 配置控制层 -->
 <bean id="UserAction"  class="com.ssh.action.UserAction"  scope="prototype">
      <property name="userService" ref="userService"></property>
 </bean>

  <!-- 配置pojo -->
 <bean id="User" class="com.ssh.pojo.User" scope="prototype"/>

 <!-- 事务管理 -->
 <bean id="transactionManager"  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
      <property name="sessionFactory">
           <ref bean="sessionFactory" />
      </property>
 </bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<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"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
 default-autowire="byName" default-lazy-init="true">
 <!--  default-autowire="byName" 根据属性名自动装配,default-lazy-init="true"  spring配置默认default-lazy-init为false,当配置为true时sping不会再去加载整个对象实例图,大大减少了初始化的时间,减少了spring的启动速度。
    这样做只是为了在开发过程中节约启动时间,在部署到实际环境中,倒是没必要设置default-lazy-init为true。毕竟部署到实际环境中不是经常的事,每次启动1分钟倒不是大问题,而且可以提高服务器效率 -->
 <!-- 配置数据源 -->
 <bean id="dataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName">
           <value>com.mysql.jdbc.Driver</value>
      </property>
      <property name="url">
           <value>jdbc:mysql://localhost/ssh?characterEncoding=utf-8</value>
      </property>
      <property name="username">
           <value>root</value>
      </property>
      <property name="password">
           <value>123</value>
      </property>
 </bean>

 <!--配置SessionFactory -->
 <bean id="sessionFactory"  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
      <property name="dataSource">
           <ref bean="dataSource" />
      </property>
      <property name="mappingResources">
           <list>
                <value>com/ssh/pojo/User.hbm.xml</value>
           </list>
     </property>
      <property name="hibernateProperties">
           <props>
                <prop key="hibernate.show_sql">true</prop>
           </props>
      </property>
 </bean>
 
 <!-- hibernateTemplate -->
 <bean id="hibernateTemplate"  class="org.springframework.orm.hibernate3.HibernateTemplate">
      <property name="sessionFactory">
           <ref bean="sessionFactory" />
      </property>
 </bean>

 <!-- 配置数据持久层 -->
 <bean id="userDao"  class="com.ssh.dao.impl.UserDaoImpl">
      <property name="hibernateTemplate" ref="hibernateTemplate"></property>
 </bean>
 
 <!-- 配置业务逻辑层 -->
 <bean id="userService"  class="com.ssh.service.impl.UserServiceImpl">
      <property name="userDao" ref="userDao"></property>
 </bean>
 
 <!-- 配置控制层 -->
 <bean id="UserAction"  class="com.ssh.action.UserAction"  scope="prototype">
      <property name="userService" ref="userService"></property>
 </bean>

  <!-- 配置pojo -->
 <bean id="User" class="com.ssh.pojo.User" scope="prototype"/>

 <!-- 事务管理 -->
 <bean id="transactionManager"  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
      <property name="sessionFactory">
           <ref bean="sessionFactory" />
      </property>
 </bean>
</beans>

Java配置可以完全替代xml配置,也是Spring boot推荐的配置方式。

以下内容引用自:

package entity;import inter.Axe;import inter.Persion;public class Chinese implements Persion { private Axe axe; private String name; public void setAxe { this.axe = axe; } public void setName(String name) { this.name = name; } @Override public void useAxe() { // TODO Auto-generated method stub System.out.println("我是:"+name+axe.chop; } }

 

 

Java 配置通过@Configuration  和 @Bean 来完成。

基于Java的配置选项,可以使你在不用配置XML的情况下编写大多数的Spring配置。

AppConfig.java

  1. @Configuration
    声明当前类是一个配置类,相当于一个Spring配置的xml文件。

  2. @Bean 注解在方法上,声明当前方法返回值是一个Java Bean。

@Configuration和@Bean注解

package inter;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import entity.Chinese;import entity.StoneAxe;@Configurationpublic class AppConfig { //相当于定义一个名为persionName的变量,其值为Jakee @Value String persionName; @Bean(name="chinese") public Persion persion() { Chinese p=new Chinese(); p.setAxe; p.setName(persionName); return p; } @Bean(name="chinese") public Axe stoneAxe() { return new StoneAxe(); }}

我们在实际开发中的原则:

带有@Configuration的注解类表示这个类可以使用Spring
IoC容器作为bean定义的来源。@Bean注解告诉Spring,一个带有@Bean的注解方法将返回一个对象,该对象应该被注册为在Spring应用程序上下文中的bean。最简单可行的@Configuration类如下所示:

  • @Configuration:用于修饰一个Java配置类。
  • Bean:用于修饰一个方法,该方法的返回值定义成容器中的一个Bean。
  • 澳门威斯尼人最新网站,Value:用于修饰一个Field,用于为该Field配置一个值,相当于配置一个变量。
  • Import:用于修饰一个Java配置类,用于向当前Java配置类中导入其他的Java配置类。
  • Scope:用于修饰一个方法,指定该方法对应的Bean的生命域。
  • Lazy:用于修饰一个方法,指定该方法对应的Bean是否需要延迟初始化。
  • DespendsOn:用于修饰一个方法,指定在在初始化对应方法之前初始化指定的Bean。
  1. 全局配置使用Java配置(数据库配置,MVC相关配置);

  2. 业务配置使用注解配置(业务Bean的配置使用注解配置@Service,
    @component,@Repository,@Controller)。

@Configuration
public class HelloWorldConfig {

    @Bean
    public HelloWorld helloWorld(){
        return new HelloWorld();
    }

}

1、如果以xml配置为主,需要在xml中加载Java配置类,代码如下:

 

对应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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" > <context:annotation-config/> <!-- 加载Java配置类 --> <bean /></beans>

实例:

<beans>
   <bean id="helloWorld" class="com.jsoft.testspring.testjavaconfiguration.HelloWorld" />
</beans>

2、如果以Java配置类为主,需要在Java配置类中加载xml配置,代码如下:

澳门威斯尼人最新网站 1

在这里,带有@Bean注解的方法名称作为bean的ID,它创建并返回实际的bean。你的配置类可以声明多个@Bean。一旦定义了配置类,你就可以使用AnnotationConfigApplicationContext来加载并把他们提供给Spring容器,如下所示:

@Configuration@ImportResource("classpath:/beans.xml")public class AppConfig(){ .............}

 

public static void main( String[] args )
{
  ApplicationContext applicationContext = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
  HelloWorld helloWorld = applicationContext.getBean(HelloWorld.class);
  helloWorld.setMessage("Hello World!");
  helloWorld.getMessage();
}
  1. 创建一个业务类

    package com.cz.javaconfig;

    /**

    • Created by Administrator on 2017/5/6.
      */
      public class FunService {

      public String sayHello(){

       return "hello world!";
      

      }
      }

当然,你可以加载各种配置类,如下所示:

 

public static void main(String[] args) {
   AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

   ctx.register(AppConfig.class, OtherConfig.class);
   ctx.register(AdditionalConfig.class);
   ctx.refresh();

   MyService myService = ctx.getBean(MyService.class);
   myService.doStuff();
}

 2. 创建一个消费业务对象类

例子:

package com.cz.javaconfig;

/**
 * Created by Administrator on 2017/5/6.
 */
public class UseUserService {

    private FunService funService;

    public void setFunService(FunService funService) {
        this.funService = funService;
    }

    public String sayHelloworld(){
        return funService.sayHello();
    }
}

pom.xml:

 

<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>com.jsoft.testspring</groupId>
  <artifactId>testjavaconfiguration</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>testjavaconfiguration</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!-- Spring Core -->
    <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

    <!-- Spring Context -->
    <!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

  </dependencies>
</project>
  1. 主角登场,创建一个JAVA配置类

    package com.cz.javaconfig;

    import org.apache.catalina.User;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;

    import javax.jws.soap.SOAPBinding;

    /**

    • Java 配置类,代替xml配置文件
    • Created by Administrator on 2017/5/6.
      */
      @Configuration
      public class JavaConfig {

      @Bean
      public FunService funService(){

       return new FunService();
      

      }

      @Bean
      public UseUserService useUserService(){

       UseUserService useUserService = new UseUserService();
       useUserService.setFunService(this.funService());
       return useUserService;
      

      }

      @Bean
      public UseUserService useUserService(FunService funService){

       UseUserService useUserService = new UseUserService();
       useUserService.setFunService(funService);
       return  useUserService;
      

      }
      }

HelloWorld.java:

 

package com.jsoft.testspring.testjavaconfiguration;

public class HelloWorld {
    private String message;

    public void setMessage(String message){
        this.message = message;
    }

    public void getMessage(){
        System.out.println(this.message);
    }
}
  1. 运行测试

    package com.cz.javaconfig;

    import org.springframework.context.annotation.AnnotationConfigApplicationContext;

    import javax.jws.soap.SOAPBinding;

    /**

    • Created by Administrator on 2017/5/6.
      */
      public class TestJavaConfig {

      public static void main(String[] args) {

       // 启动Spring上下文,并初始化配置文件
       AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
       UseUserService useUserService = context.getBean(UseUserService.class);
       System.out.printf(useUserService.sayHelloworld());
      

      }
      }

HelloWorldConfig.java:

 

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HelloWorldConfig {

    @Bean
    public HelloWorld helloWorld(){
        return new HelloWorld();
    }

}

 

App.java:

澳门威斯尼人最新网站 2

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
        HelloWorld helloWorld = applicationContext.getBean(HelloWorld.class);
        helloWorld.setMessage("Hello World!");
        helloWorld.getMessage();
    }
}

 

测试结果:

澳门威斯尼人最新网站 3

 

测试工程:

Bean的依赖性注入**

当Beans依赖对方时,表达这种依赖性非常简单,只要有一个bean方法调用另一个,如下所示:

@Configuration
public class HelloWorldConfig {

    @Bean
    public HelloWorld helloWorld(){
        return new HelloWorld(message());
    }

    @Bean
    public String message(){
        return new String("Hello World");
    }

}

可以看出,有依赖性时直接在类中调用新建的方法即可。

例子:

pom.xml:

<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>com.jsoft.testspring</groupId>
  <artifactId>testjavaconfiguration</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>testjavaconfiguration</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!-- Spring Core -->
    <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

    <!-- Spring Context -->
    <!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

  </dependencies>
</project>

HelloWorld.java:

package com.jsoft.testspring.testjavaconfiguration;

public class HelloWorld {
    private String message;

    public HelloWorld(String message){
        this.message = message;
    }

    public void getMessage(){
        System.out.println(this.message);
    }
}

HelloWorldConfig.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HelloWorldConfig {

    @Bean
    public HelloWorld helloWorld(){
        return new HelloWorld(message());
    }

    @Bean
    public String message(){
        return new String("Hello World");
    }

}

App.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
        HelloWorld helloWorld = applicationContext.getBean(HelloWorld.class);
        helloWorld.getMessage();
    }
}

测试结果:

澳门威斯尼人最新网站 4

 

测试工程:

@Import注释

@import注解允许从另一个配置类中加载Bean定义。如下所示:

@Configuration
public class ConfigA {
   @Bean
   public A a() {
      return new A(); 
   }
}

@Configuration
@Import(ConfigA.class)
public class ConfigB {
   @Bean
   public B b() {
      return new B(); 
   }
}

现在,当实例化上下文时,不需要同时指定ConfigA.class和ConfigB.class,只要ConfigB类需要提供,如下所示:

public static void main(String[] args) {
   ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);

   A a = ctx.getBean(A.class);
   B b = ctx.getBean(B.class);
}

例子:

pom.xml:

<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>com.jsoft.testspring</groupId>
  <artifactId>testjavaconfiguration</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>testjavaconfiguration</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!-- Spring Core -->
    <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

    <!-- Spring Context -->
    <!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

  </dependencies>
</project>

HelloWorld.java:

package com.jsoft.testspring.testjavaconfiguration;

public class HelloWorld {
    private String message;

    public HelloWorld(String message){
        this.message = message;
    }

    public void getMessage(){
        System.out.println(this.message);
    }
}

HelloWorldConfig.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HelloWorldConfig {

    @Bean
    public HelloWorld helloWorld(){
        return new HelloWorld(message());
    }

    @Bean
    public String message(){
        return new String("Hello World");
    }

}

HelloWorldConfigB.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(HelloWorldConfig.class)
public class HelloWorldConfigB {

    @Bean
    public String messageB(){
        return new String("Hello B");
    }
}

App.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(HelloWorldConfigB.class);
        HelloWorld helloWorld = applicationContext.getBean(HelloWorld.class);
        helloWorld.getMessage();
    }
}

可以看出不用再次引用HelloWorldConfig.java类了。

测试结果:

澳门威斯尼人最新网站 5

 

测试工程:

生命周期回调

@Bean注解支持指定任意的初始化和销毁​​回调方法,这与Spring元素中的Spring
XML的init-method和destroy-method属性非常相似。如下所示:

public class Foo {
   public void init() {

   }
   public void cleanup() {

   }
}

@Configuration
public class AppConfig {
   @Bean(initMethod = "init", destroyMethod = "cleanup" )
   public Foo foo() {
      return new Foo();
   }
}

例子:

pom.xml:

<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>com.jsoft.testspring</groupId>
  <artifactId>testjavaconfiguration</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>testjavaconfiguration</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!-- Spring Core -->
    <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

    <!-- Spring Context -->
    <!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

  </dependencies>
</project>

HelloWorld.java:

package com.jsoft.testspring.testjavaconfiguration;

public class HelloWorld {
    private String message;

    public HelloWorld(String message){
        this.message = message;
    }

    public void getMessage(){
        System.out.println(this.message);
    }

    public void init(){
        System.out.println("HelloWorld init");
    }

    public void cleanup(){
        System.out.println("HelloWorld cleanup");
    }
}

HelloWorldConfig.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HelloWorldConfig {

    @Bean(initMethod="init",destroyMethod="cleanup")
    public HelloWorld helloWorld(){
        return new HelloWorld(message());
    }

    @Bean
    public String message(){
        return new String("Hello World");
    }

}

App.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        AbstractApplicationContext applicationContext = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
        HelloWorld helloWorld = applicationContext.getBean(HelloWorld.class);
        helloWorld.getMessage();
        applicationContext.registerShutdownHook();
    }
}

测试结果:

澳门威斯尼人最新网站 6

 

测试工程:

指定Bean的作用域范围

默认范围是单实例,但是你可以重写带有@Scope注解的方法,如下所示:

@Configuration
public class AppConfig {
   @Bean
   @Scope("prototype")
   public Foo foo() {
      return new Foo();
   }
}

例子:

pom.xml:

<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>com.jsoft.testspring</groupId>
  <artifactId>testjavaconfiguration</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>testjavaconfiguration</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!-- Spring Core -->
    <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

    <!-- Spring Context -->
    <!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

  </dependencies>
</project>

HelloWorld.java:

package com.jsoft.testspring.testjavaconfiguration;

public class HelloWorld {
    private String message;

    public void setMessage(String message){
        this.message = message;
    }

    public void getMessage(){
        System.out.println(this.message);
    }
}

HelloWorldConfig.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class HelloWorldConfig {

    @Bean
    @Scope("prototype")
    public HelloWorld helloWorld(){
        return new HelloWorld();
    }

}

@Scope的值和xml中配置的保持一致。

App.java:

package com.jsoft.testspring.testjavaconfiguration;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
        HelloWorld helloWorld = applicationContext.getBean(HelloWorld.class);
        helloWorld.setMessage("Hello World 1!");
        helloWorld.getMessage();
        HelloWorld helloWorld2 = applicationContext.getBean(HelloWorld.class);
        helloWorld2.getMessage();
    }
}

测试结果:

澳门威斯尼人最新网站 7

 

测试工程:

更多Java配置的官方例子参考:

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图