【问题标题】:Hidden features of Spring framework? [closed]Spring框架的隐藏特性? [关闭]
【发布时间】:2009-09-12 23:21:11
【问题描述】:

在看到许多关于编程语言的隐藏特性之后,我想知道 Spring“事实上的”框架的隐藏特性。如您所知,Spring 文档隐藏了许多特性,很高兴分享。

而你:你知道 Spring 框架的哪些隐藏特性?

【问题讨论】:

    标签: java spring


    【解决方案1】:

    Spring 内置了强大的StringUtils

    请注意以下包含一组 id 的数组

    String [] idArray = new String [] {"0", "1", "2", "0", "5", "2"} 
    

    并且您想删除重复的引用。去做吧

    idArray = StringUtils.removeDuplicateStrings(idArray);
    

    现在 idArray 将包含 {"0", "1", "2", "5"}。

    还有更多。


    是否可以使用 Controller 类而不在 Web 应用程序上下文文件中声明它们?

    是的,只需将@Component 放入其声明中(@Controller 无法按预期工作)

    package br.com.spring.view.controller
    
    @Component
    public class PlayerController extends MultiActionController {
    
        private Service service;
    
        @Autowired
        public PlayerController(InternalPathMethodNameResolver ipmnr, Service service) {
            this.service = service;
    
            setMethodNameResolver(ipmnr);
        }
    
        // mapped to /player/add
        public ModelAndView add(...) {}
    
        // mapped to /player/remove
        public ModelAndView remove(...) {}
    
        // mapped to /player/list
        public ModelAndView list(...) {}
    
    }
    

    所以在 web 应用程序上下文文件中放入以下内容

    <beans ...>
        <context:component-scan base-package="br.com.spring.view"/>
        <context:annotation-config/>
        <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
            <property name="order" value="0"/>
            <property name="caseSensitive" value="true"/>
        </bean>
        <bean class="org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver"/>
    </beans>
    

    没有别的


    动态形式的验证?

    使用下面的

    public class Team {
    
        private List<Player> playerList;    
    
    }
    

    所以在团队验证器中放置

    @Component
    public class TeamValidator implements Validator {
    
        private PlayerValidator playerValidator;
    
        @Autowired
        public TeamValidator(PlayerValidator playerValidator) {
            this.playerValidator = playerValidator;
        }
    
        public boolean supports(Class clazz) {
            return clazz.isAssignableFrom(Team.class);
        }
    
        public void validate(Object command, Errors errors) {
            Team team = (Team) command;
    
            // do Team validation
    
            int index = 0;
            for(Player player: team.getPlayerList()) {
                // Notice code just bellow
                errors.pushNestedPath("playerList[" + index++ + "]");
    
                ValidationUtils.invokeValidator(playerValidator, player, errors);
    
                errors.popNestedPath();
            }
    
        }
    
    }
    

    Web 表单中的继承?

    将 ServlerRequestDataBinder 与隐藏表单标志一起使用

    public class Command {
    
        private Parent parent;
    
    }
    
    public class Child extends Parent { ... }
    
    public class AnotherChild extends Parent { ... }
    

    然后在您的控制器中执行以下操作

    public class MyController extends MultiActionController {
    
        public ModelAndView action(HttpServletRequest request, HttpServletResponse response, Object command) {
    
            Command command = (Command) command;
    
            // hidden form flag
            String parentChildType = ServletRequestUtils.getRequiredStringParameter(request, "parentChildType");
    
            // getApplicationContext().getBean(parentChildType) retrieves a Parent object from a application context file
            ServletRequestDataBinder binder = 
                new ServletRequestDataBinder(getApplicationContext().getBean(parentChildType));
    
            // populates Parent child object
            binder.bind(request);
    
            command.setParent((Parent) binder.getTarget());
    }
    

    Spring 有一个内置的扫描器类ClassPathScanningCandidateComponentProvider。例如,您可以使用它来查找注释。

    ClassPathScanningCandidateComponentProvider scanner =
        new ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFAULT_FILTER>);
    
    scanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));
    
    for (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>))
        System.out.println(bd.getBeanClassName());
    

    Spring 有一个有用的org.springframework.util.FileCopyUtils 类。您可以使用复制上传的文件

    public ModelAndView action(...) throws Exception {
    
        Command command = (Command) command;
    
        MultiPartFile uploadedFile = command.getFile();
    
        FileCopyUtils.copy(uploadedFile.getBytes(), new File("destination"));
    

    如果您使用基于注解的控制器(Spring 2.5+)或普通的 MVC Spring 控制器,您可以使用 WebBindingInitializer 来注册全局属性编辑器。类似的东西

    public class GlobalBindingInitializer implements WebBindingInitializer {
    
        public void initBinder(WebDataBinder binder, WebRequest request) {
            binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy", true);
        }
    
    }
    

    所以在你的网络应用上下文文件中,声明

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">
            <bean class="GlobalBindingInitializer"/>
        </property>
    </bean>
    

    这样任何基于注解的控制器都可以使用在 GlobalBindingInitializer 中声明的任何属性编辑器。

    等等……

    【讨论】:

      【解决方案2】:

      Spring 可以用作事件总线的替代品,因为 ApplicationContext 也是 ApplicationEventPublisher

      参考 Spring 实现可以在SimpleApplicationEventMulticaster 中找到,它可以选择使用线程池来异步分发事件。

      【讨论】:

      • 有用的东西,这个。完成这项工作的代码是SimpleApplicationEventMulticaster,它可以选择使用线程池来异步分发事件。我已经厌倦了编写代码来做到这一点。
      【解决方案3】:

      一种是使用基于 CGLib 的类代理来实现 Spring 的 AOP。它也可以通过 Java 的动态代理来完成,但默认是 CGLib。因此,如果您在堆栈跟踪中看到 CGLib,请不要感到惊讶。

      其他是使用 AOP 进行 DI。是的,在你不知道的情况下,到处都是 AOP。很高兴知道您的代码是基于 AOP 的,即使您只是将 Spring 用于 DI 目的。

      【讨论】:

        【解决方案4】:

        在运行时热交换 spring bean。

        这对测试很有用。

        here

        【讨论】:

          【解决方案5】:

          在 Spring 中查找任何 隐藏 功能的最佳方法是只需要查看源代码。

          虽然 Spring 在注解、AspectJ 和 DI 的使用方面非常灵活,但很难说什么是隐藏特性。

          【讨论】:

            【解决方案6】:

            与典型的专有软件不同,Spring 的源代码可供任何愿意下载的人免费使用。

            因此 Spring 没有隐藏的特性。它只是您还没有见过的功能......。

            【讨论】:

              猜你喜欢
              • 2010-09-05
              • 2010-10-12
              • 2010-10-20
              • 1970-01-01
              • 2010-11-05
              • 2010-10-17
              • 2017-10-13
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多