• 【Spring】Spring,我的零散使用杂记


    通过Java类设置配置信息,JavaConfig

    Spring常用的通过XML或者@Controller、@Servoce、@Repository、@Component等注解注册Bean,最近看Spring Session的源码,知道还有JavaConfig注册Bean的方式,就是通过@Configuration@Bean注册Bean。

    引用依赖包:

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.10.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.2.10.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.2</version>
        </dependency>
    
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>
    </dependencies>
    

    这个类是配置Bean的:

    package com.nicchagil;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class UserConfiguration {
        
        @Bean
        public UserService userService(UserDAO userDAO) {
            return new UserService();
        }
        
        @Bean
        public UserDAO userDAO() {
            return new UserDAO();
        }
    
    }
    

    这两个Bean是这样的:

    package com.nicchagil;
    
    public class UserDAO {
    
    }
    
    package com.nicchagil;
    
    public class UserService {
    
    }
    

    这个BeanPostProcessor是用于看Bean有没有实例化的,与JavaConfig本身没什么关系:

    package com.nicchagil;
    
    import java.util.logging.Logger;
    
    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.config.BeanPostProcessor;
    
    public class MyBeanPostProcessor implements BeanPostProcessor {
        
        Logger logger = Logger.getLogger("MyBeanPostProcessor");
        
        public Object postProcessBeforeInitialization(Object obj, String arg1)
                throws BeansException {
            return obj;
        }
    
        public Object postProcessAfterInitialization(Object obj, String arg1)
                throws BeansException {
            if (obj != null) {
                logger.info("实例化:" + obj + ", Class:" + obj.getClass().getName());
            }
            
            return obj;
        }
    
    }
    

    记得要注册扫描包的路径:

    <?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-3.0.xsd
               http://www.springframework.org/schema/context 
               http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
        <!-- scan the component from the base package -->
        <context:component-scan base-package="com.nicchagil" />
        
        <bean id="myBeanPostProcessor" class="com.nicchagil.MyBeanPostProcessor" />
        
    </beans>
    

    测试类:

    package com.nicchagil;
    
    import java.util.logging.Logger;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class HowToUse {
        
        public static Logger LOGGER = Logger.getLogger("HowToUse");
    
        public static void main(String[] args) {
            ApplicationContext context =
                    new ClassPathXmlApplicationContext("spring.xml");
            
            UserDAO userDAO = context.getBean("userDAO", UserDAO.class);
            LOGGER.info("userDAO : " + userDAO);
            UserService userService = context.getBean("userService", UserService.class);
            LOGGER.info("userService : " + userService);
        }
    
    }
    

    运行日志:

    六月 11, 2017 3:41:57 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
    信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@37f8bb67: startup date [Sun Jun 11 15:41:57 CST 2017]; root of context hierarchy
    六月 11, 2017 3:41:57 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    信息: Loading XML bean definitions from class path resource [spring.xml]
    六月 11, 2017 3:41:58 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
    信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1d057a39: defining beans [userConfiguration,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,myBeanPostProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,userService,userDAO]; root of factory hierarchy
    六月 11, 2017 3:41:58 下午 com.nicchagil.MyBeanPostProcessor postProcessAfterInitialization
    信息: 实例化:com.nicchagil.UserConfiguration$$EnhancerBySpringCGLIB$$cd2ac8bb@32eebfca, Class:com.nicchagil.UserConfiguration$$EnhancerBySpringCGLIB$$cd2ac8bb
    六月 11, 2017 3:41:58 下午 com.nicchagil.MyBeanPostProcessor postProcessAfterInitialization
    信息: 实例化:com.nicchagil.UserDAO@47db50c5, Class:com.nicchagil.UserDAO
    六月 11, 2017 3:41:58 下午 com.nicchagil.MyBeanPostProcessor postProcessAfterInitialization
    信息: 实例化:com.nicchagil.UserService@149494d8, Class:com.nicchagil.UserService
    六月 11, 2017 3:41:58 下午 com.nicchagil.HowToUse main
    信息: userDAO : com.nicchagil.UserDAO@47db50c5
    六月 11, 2017 3:41:58 下午 com.nicchagil.HowToUse main
    信息: userService : com.nicchagil.UserService@149494d8
    

    自定义逻辑创建Bean的工厂Bean,FactoryBean

    引入POM:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>3.2.10.RELEASE</version>
    </dependency>
    

    声明实体:

    package com.nicchagil.factorybeanexercise;
    
    public class User {
    
        private Integer id;
        private String name;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "User [id=" + id + ", name=" + name + "]";
        }
        
    }
    

    定义工厂:

    package com.nicchagil.factorybeanexercise;
    
    import org.springframework.beans.factory.FactoryBean;
    
    public class UserFactoryBean implements FactoryBean<User> {
    
        /**
         * 获取对象
         */
        @Override
        public User getObject() throws Exception {
            User user = new User();
            user.setId(123);
            user.setName("Nick Huang");
            return user;
        }
    
        /**
         * 获取对象的类型
         */
        @Override
        public Class<?> getObjectType() {
            return User.class;
        }
    
        /**
         * 对象是否单例
         */
        @Override
        public boolean isSingleton() {
            return true;
        }
        
    }
    

    注册工厂:

    <?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-3.0.xsd
               http://www.springframework.org/schema/context 
               http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
        <bean id="user" class="com.nicchagil.factorybeanexercise.UserFactoryBean" />
        
    </beans>
    

    测试类:

    package com.nicchagil.factorybeanexercise;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class HowToTest {
    
        public static void main(String[] args) {
            @SuppressWarnings("resource")
            ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
            
            User user = ac.getBean("user", User.class);
            System.out.println(user);
        }
    
    }
    
  • 相关阅读:
    利用Continuous Testing实现Eclipse环境自动单元测试
    GWT-Dev-Plugin(即google web toolkit developer plugin)for Chrome的安装方法
    在SQL Server 2012中实现CDC for Oracle
    在SSIS 2012中使用CDC(数据变更捕获)
    SQL Server Data Tools – Business Intelligence for Visual Studio 2012安装时提示“The CPU architecture....”的解决方法
    SQL Server 2012新特性(1)T-SQL操作FileTable目录实例
    RHEL每天定时备份Oracle
    GWT-Dev-Plugin(即google web toolkit developer plugin)for firefox的下载地址
    Oracle中修改表名遇到“ORA-00054: 资源正忙, 但指定以 NOWAIT 方式获取资源, 或者超时失效”
    Oracle中序列(SEQUENCE)的使用一例
  • 原文地址:https://www.cnblogs.com/nick-huang/p/6985352.html
Copyright © 2020-2023  润新知