小编Ari*_*deh的帖子

MVC与Flux?双向与单向?

查看下图(解释MVC),我看到了单向数据流.

那么为什么我们认为MVC具有双向数据流,同时证明Flux的合理性呢?

MVC模式

model-view-controller flux reactjs

37
推荐指数
4
解决办法
1万
查看次数

在Java中删除ArrayList的最后一个对象

我想快速删除最后一个对象ArrayList.

我知道remove(Object O)接受O(n)一个ArrayList,但我想知道是否有可能在恒定时间内这样做,因为我只想删除最后一个对象?

java arraylist data-structures

36
推荐指数
1
解决办法
5万
查看次数

Spring启动控制器 - 将Multipart和JSON上传到DTO

我想将表单中的文件上传到Spring Boot API端点.

UI是用React编写的:

export function createExpense(formData) {
  return dispatch => {
    axios.post(ENDPOINT,
      formData, 
      headers: {
        'Authorization': //...,
        'Content-Type': 'application/json'
      }
      ).then(({data}) => {
        //...
      })
      .catch(({response}) => {
        //...
      });
    };
}

  _onSubmit = values => {
    let formData = new FormData();
    formData.append('title', values.title);
    formData.append('description', values.description);
    formData.append('amount', values.amount);
    formData.append('image', values.image[0]);
    this.props.createExpense(formData);
  }
Run Code Online (Sandbox Code Playgroud)

这是java端代码:

@RequestMapping(path = "/{groupId}", method = RequestMethod.POST)
public ExpenseSnippetGetDto create(@RequestBody ExpensePostDto expenseDto, @PathVariable long groupId, Principal principal, BindingResult result) throws IOException {
   //..
}
Run Code Online (Sandbox Code Playgroud)

但是我在java方面得到了这个例外:

org.springframework.web.HttpMediaTypeNotSupportedException: Content …
Run Code Online (Sandbox Code Playgroud)

javascript java spring-boot

23
推荐指数
3
解决办法
3万
查看次数

@Transcational测试类会影响事务服务层的工作方式

我正在为我的Spring启动应用程序Rest控制器编写集成测试.

当我用@Transactional它注释测试类时,它没有按预期工作,当我删除注释时,它传递正常.

  1. @Transactional在测试类上使用是否意味着什么都没有写入db?我的其他测试工作正常!他们或多或少地做同样的工作.他们写/更新/读取,但此测试测试删除端点.

  2. 如果使用@Transactional注释测试类意味着无法控制数据持久性,为什么人们甚至在测试中使用它?我注入实体管理器测试类,并呼吁flushclear,它并没有帮助.

  3. 即使数据没有写入数据库,它们仍然存在,对吧?不调用repository.delete应该从持久化上下文中删除该项吗?

  4. 不影响db(delete)的代码位于Service层.它是在Controller中调用的,我正在测试,而不是测试类.无论测试类是否注释,我都希望它能够正常工作@Transacational.

注意服务层是@Transactional

它位于服务层中,由控制器调用.它不是测试中的形式.

public void delete(long groupId, String username) {
    Group group = this.loadById(groupId);
    User user = userService.loadByUsername(username);
    groupRepository.delete(groupId);
}
Run Code Online (Sandbox Code Playgroud)

编辑1

失败的测试代码:

/*
 * Deleting a group shouldn't delete the members of that group
 */
@Test
public void testDeleteGroupWithMembers() throws Exception {
    Principal mockPrincipal = Mockito.mock(Principal.class);
    Mockito.when(mockPrincipal.getName()).thenReturn(DUMMY_USERNAME);

    User admin = userTestingUtil.createUser(DUMMY_USERNAME, DUMMY_USER_NAME, null, null);
    Group group = groupTestingUtil.createGroup(DUMMY_GROUP_NAME, DUMMY_GROUP_DESCRIPTION, DUMMY_IMAGE_ID, admin);

    User …
Run Code Online (Sandbox Code Playgroud)

java hibernate

19
推荐指数
2
解决办法
788
查看次数

使用内存中的数据库为Rest控制器编写测试

我正在为Spring boot Rest控制器编写测试.此休止控制器将一些值写入db.

我想使用Spring为此测试提供的内存数据库.根据这个文档,我必须使用注释测试类@DataJpaTest,这会导致此错误:

java.lang.IllegalStateException: Failed to load ApplicationContext
Run Code Online (Sandbox Code Playgroud)

在错误堆栈跟踪中,我看到引发了以下异常:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath or tune the replace attribute of @AutoconfigureTestDatabase. …

java testing spring spring-boot

12
推荐指数
1
解决办法
4309
查看次数

在非交互模式下递归安装和卸载 pip

作为我的 bash 脚本的一部分,我想以非交互模式安装和卸载我在文件中具有它们名称的 pip 依赖项。我能够搜索并找到这些命令:

pip3 uninstall --yes -r host-requirements.txt
pip3 install --no-input -r host-requirements.txt
Run Code Online (Sandbox Code Playgroud)

我无法在 pip 的帮助文档中找到--yes&--no-input选项,我不确定它们是否得到官方支持。

python pip

12
推荐指数
1
解决办法
9107
查看次数

Spring启动测试不遵守Web安全配置

我正在为Rest API控制器编写测试.无需任何授权即可访问此端点:

@EnableWebSecurity
@Configuration
@Import(AppConfig.class)
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired 
private UserDetailsRepository accountRepository;

@Autowired
private CustomUserDetailsService customUserDetailsService;

@Autowired
private JWTAuthenticationFilter jwtAuthenticationFilter;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
        .authorizeRequests()
            .anyRequest().authenticated().and()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

/*
 * Apparently, permitAll() doesn't work for custom filters, therefore we ignore the signup and login endpoints 
 * here
 */
@Override
public void configure(WebSecurity web)
        throws Exception {
    web.ignoring()
        .antMatchers(HttpMethod.POST, "/login")
        .antMatchers(HttpMethod.POST, "/signup");
}

/*
 * set user details services and …
Run Code Online (Sandbox Code Playgroud)

java security spring spring-boot

11
推荐指数
1
解决办法
2640
查看次数

Spring将浏览器访问者与API调用区分为端点

在我的Spring启动应用程序中,我有很多端点/api/**.以下是我的App配置:

@Configuration
public class AppConfig extends WebMvcConfigurerAdapter {

    private class PushStateResourceResolver implements ResourceResolver {
        private Resource index = new ClassPathResource("/public/index.html");
        private List<String> handledExtensions = Arrays.asList("html", "js",
                "json", "csv", "css", "png", "svg", "eot", "ttf", "woff",
                "appcache", "jpg", "jpeg", "gif", "ico");

        private List<String> ignoredPaths = Arrays.asList("^api\\/.*$");

        @Override
        public Resource resolveResource(HttpServletRequest request,
                String requestPath, List<? extends Resource> locations,
                ResourceResolverChain chain) {
            return resolve(requestPath, locations);
        }

        @Override
        public String resolveUrlPath(String resourcePath,
                List<? extends Resource> locations, ResourceResolverChain chain) {
            Resource resolvedResource = resolve(resourcePath, …
Run Code Online (Sandbox Code Playgroud)

java spring spring-boot

9
推荐指数
1
解决办法
1059
查看次数

AuthenticationProcessingFilter和WebSecurityConfigurerAdapter导致循环依赖

在我的Spring启动应用程序中,我有以下两个类:

@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        // TODO re-enable csrf after dev is done
        .csrf()
            .disable()
            // we must specify ordering for our custom filter, otherwise it
            // doesn't work
            .addFilterAfter(jwtAuthenticationFilter,
                    UsernamePasswordAuthenticationFilter.class)
            // we don't need Session, as we are using jwt instead. Sessions
            // are harder to scale and manage
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
   } …
Run Code Online (Sandbox Code Playgroud)

java spring

9
推荐指数
1
解决办法
198
查看次数

ModelMapper:确保该方法的参数为零,并且不返回void

我为模型映射器配置了以下配置,以将User类的实例转换为实例ExtendedGetUserDto.

    public ExtendedGetUserDto convertToExtendedDto(User user) {
        PropertyMap<User, ExtendedGetUserDto> userMap = new PropertyMap<User, ExtendedGetUserDto>() {
            protected void configure() {
                map().setDescription(source.getDescription());
                map().setId(source.getId());
//              map().setReceivedExpenses(
//                      source.getReceivedExpenses()
//                              .stream()
//                              .map(expense -> expenseDtoConverter.convertToDto(expense))
//                              .collect(Collectors.toSet())
//                      );
                Set<GetInvitationDto> result = new HashSet<GetInvitationDto>();
                for (Invitation inv: source.getReceivedInvitations()) {
                    System.out.println("HELLO");
                    //result.add(null);
                }
                //map().setReceivedInvitations(result);
            }
        };
        modelMapper.addMappings(userMap);
        return modelMapper.map(user, ExtendedGetUserDto.class);
    }
Run Code Online (Sandbox Code Playgroud)

在评论之前setReceivedExpense我收到了这个错误:

org.modelmapper.ConfigurationException: ModelMapper configuration errors:

1) Invalid source method java.util.stream.Stream.map(). Ensure that method has zero parameters and does not …
Run Code Online (Sandbox Code Playgroud)

java spring modelmapper

8
推荐指数
1
解决办法
3176
查看次数