Spring_4

出处:http://www.cnblogs.com/JsonShare

 

Spring学习(13)--- 基于Java类的配置Bean 之 @Configuration & @Bean注解

 

      基于Java配置选项,可以编写大多数的Spring不用配置XML,但有几个基于Java的注释的帮助下解释。从Spring3.0开始支持使用java代码来代替XML来配置Spring,基于Java配置Spring依靠Spring的JavaConfig项目提供的很多优点。通过使用@Configuration, @Bean ,@Import ,@DependsOn 来实现Java配置Spring.

1) @Configuration & @Bean 注解:

      在Spring的新的Java-Configuration的中间产物是基于类的@Configuration的注解和基于方法的@Bean注解。            

      @Bean注解是用来指明方法的实例化,配置和初始化一个对象是通过Spring的IoC容器来管理的。对于那些熟悉使用以XML配置Spring的<beans /> 标签,@Bean注解和<bean />标签是起相同作用的。可以在Spring的@Component注解中的类使用@Bean注解任何方法(仅仅是可以),但是,通常使用的是@Configuration

      @Configuration注解的类指明该类主要是作为一个bean的来源定义。此外,@Configuration定义的classes允许在同一个类中使用@Bean定义的方法来定义依赖的bean

      注释类与@Configuration表示这个类可以使用Spring IoC容器为bean定义来源。在@Bean 注解告诉Spring的注解为@Bean的一个方法将返回应注册为在Spring应用程序上下文中的bean对象。

1
2
3
4
5
6
7
8
@Configuration
public class MovieFinder {
 
    @Bean
    public InjectionService injectionService(){
        return new InjectionServiceImpl();
    }
}

 上面的代码将等同于下面的XML配置:

1
<bean id="movieFinder " class="com.mypackage.MovieFinder"></bean> 

 例子:

定义Store接口,及实现类StoreImpl

1
2
3
4
5
package com.beanannotation;
 
public interface Store {
 
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.beanannotation;
 
 
public class StoreImpl implements Store {
 
    public void init(){
        System.out.println("this is init.");
    }
     
    public void destory(){
        System.out.println("this is destory.");
    }
}

 定义StoreConfig:注意,不指定@Bean的name属性时,默认的name为方法名(即此例子的getStore)

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.beanannotation;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class StoreConfig {
 
    @Bean(name="store",initMethod="init",destroyMethod="destory")//若不指定name,默认为方法名
    public Store getStore(){
        return new StoreImpl();
    }
}

  XML配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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-4.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.1.xsd">
         
        <context:component-scan base-package="com.beanannotation">
        </context:component-scan>
         
</beans>

 单元测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.beanannotation;
 
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
 
public class UnitTest {
     
    @Test
    public void test(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-beanannotation.xml"); 
        Store service=(Store)context.getBean("store");
        System.out.println(service.getClass().getName());
        context.close();   // 关闭 Spring 容器,以触发 Bean 销毁方法的执行
    }
}

 结果:

复制代码
2015-7-7 16:13:25 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@36b8bef7: startup date [Tue Jul 07 16:13:25 CST 2015]; root of context hierarchy
2015-7-7 16:13:25 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring-beanannotation.xml]
this is init.
2015-7-7 16:13:25 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@36b8bef7: startup date [Tue Jul 07 16:13:25 CST 2015]; root of context hierarchy
com.beanannotation.StoreImpl
this is destory.
复制代码

 

 

Spring学习(14)--- 基于Java类的配置Bean 之 @ImportResource & @Value 注解

 

学习如何使用@ImportResource 和 @Value 注解进行资源文件读取

例子:

先创建一个MyDriverManager类(模拟读取数据库配置信息)

1
2
3
4
5
6
7
8
9
10
package com.beanannotation;
 
public class MyDriverManager {
 
    public MyDriverManager(String url,String username,String password){
        System.out.println("url : "+url);
        System.out.println("username : "+username);
        System.out.println("password : "+password);
    }
}

 创建StoreConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.beanannotation;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
 
@Configuration
@ImportResource("classpath:config.xml")
public class StoreConfig {
 
    @Value("${url}")
    private String url;
     
    @Value("${username}")
    private String username;
     
    @Value("${password}")
    private String password;
     
    @Bean
    public MyDriverManager myDriverManager(){
        return new MyDriverManager(url,username,password);
    }
}

XML配置(context:property-placeholder 指定资源文件的位置)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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-4.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.1.xsd">
         
     <context:property-placeholder location="classpath:config.properties"/>
 
     <context:component-scan base-package="com.beanannotation">
     </context:component-scan>
      
         
</beans>

  创建资源文件config.properties

1
2
3
url=127.0.0.1
username=root
password=123456

 单元测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.beanannotation;
 
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
 
public class UnitTest {
     
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-beanannotation.xml"); 
        MyDriverManager service=(MyDriverManager)context.getBean("myDriverManager");
        System.out.println(service.getClass().getName());
         
    }
}

 结果:

复制代码
2015-7-7 17:22:25 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@36b8bef7: startup date [Tue Jul 07 17:22:25 CST 2015]; root of context hierarchy
2015-7-7 17:22:25 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [config.xml]
2015-7-7 17:22:25 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [config.xml]
2015-7-7 17:22:25 org.springframework.context.support.PropertySourcesPlaceholderConfigurer loadProperties
信息: Loading properties file from class path resource [config.properties]
2015-7-7 17:22:25 org.springframework.context.support.PropertySourcesPlaceholderConfigurer loadProperties
信息: Loading properties file from class path resource [config.properties]
url : 127.0.0.1
username : Administrator
password : 123456
com.beanannotation.MyDriverManager
复制代码

PS:有没有发现结果有异常----username 不是root 而是计算机的当前用户名

@Value("${username}") 在取值的时候,会去取当前用户的名称

所以在以后的使用中,要避免使用username

 

所以,修改一下config.properties 和StoreConfig

1
2
3
jdbc.url=127.0.0.1
jdbc.username=root
jdbc.password=123456

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.beanannotation;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
 
@Configuration
@ImportResource("classpath:config.xml")
public class StoreConfig {
 
    @Value("${jdbc.url}")
    private String url;
     
    @Value("${jdbc.username}")
    private String username;
     
    @Value("${jdbc.password}")
    private String password;
     
    @Bean
    public MyDriverManager myDriverManager(){
        return new MyDriverManager(url,username,password);
    }
}

 测试同上:

结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
2015-7-7 17:26:41 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@32bf7190: startup date [Tue Jul 07 17:26:41 CST 2015]; root of context hierarchy
2015-7-7 17:26:41 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [config.xml]
2015-7-7 17:26:41 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [config.xml]
2015-7-7 17:26:41 org.springframework.context.support.PropertySourcesPlaceholderConfigurer loadProperties
信息: Loading properties file from class path resource [config.properties]
2015-7-7 17:26:41 org.springframework.context.support.PropertySourcesPlaceholderConfigurer loadProperties
信息: Loading properties file from class path resource [config.properties]
url : 127.0.0.1
username : root
password : 123456
com.beanannotation.MyDriverManager

 这下就可以了

 

Spring学习(15)--- 基于Java类的配置Bean 之 @Bean & @Scope 注解

 

默认@Bean是单例的,但可以使用@Scope注解来覆盖此如下:

1
2
3
4
5
6
7
8
9
@Configuration
public class MyConfiguration {
 
    @Bean
    @Scope("prototype")
    public MovieCatalog movieCatalog(){
        //...
    }
}

 Bean的作用域包括singleton、prototype、request、session、global session

例子:

 新建接口Store及实现类StoreImpl

1
2
3
4
5
package com.scope;
 
public interface Store {
 
}

 

1
2
3
4
5
package com.scope;
 
public class StoreImpl implements Store {
     
}

 java config 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.scope;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
 
@Configuration
public class StoreConfig {
 
    @Bean
    @Scope("prototype")
    public Store stringStore(){
        return new StoreImpl();
    }
}

 XML配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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-4.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.1.xsd">
         
        <context:component-scan base-package="com.scope">
        </context:component-scan>
         
</beans>

 单元测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.scope;
 
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
 
public class UnitTest {
     
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-beanannotation.xml"); 
        Store store=(Store)context.getBean("stringStore");
        System.out.println(store.hashCode());
         
        Store store2=(Store)context.getBean("stringStore");
        System.out.println(store2.hashCode());
         
    }
}

 结果:

复制代码
2015-7-8 9:47:11 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@36b8bef7: startup date [Wed Jul 08 09:47:11 CST 2015]; root of context hierarchy
2015-7-8 9:47:11 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring-beanannotation.xml]
1152423575
628012732
复制代码

结果发现,两个对象的hashcode不一样,说明每次取出的都是新的对象。

posted @ 2017-04-19 17:57  charles999  阅读(86)  评论(0编辑  收藏  举报