弹簧框架的隐藏功能?[已关闭]

2022-09-01 15:46:31

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

而你:你知道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();
        }

    }

}

网络表单中的继承 ?

使用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);
    }

}

因此,在 Web 应用程序上下文文件中,声明

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

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

等等...


答案 2

Spring可以用作事件总线的替代品,因为ExportalContext也是AdplicationEventPublisher。

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


推荐