小编Joa*_*sta的帖子

如何正确地进行依赖注入(在Spring中)?

我怀疑使用Spring将对象注入到类中.我在我的项目中使用了这种代码:

@Resource // or @Autowired even @Inject
private PersonRepository personRepository;
Run Code Online (Sandbox Code Playgroud)

然后在方法上正常使用它:

personRepository.save(p);
Run Code Online (Sandbox Code Playgroud)

否则我在Spring示例中找到了注入构造函数:

private final PersonRepository personRepository;

@Autowired
public PersonController(PersonRepository personRepository) {
  this.personRepository = personRepository;
}
Run Code Online (Sandbox Code Playgroud)

那两个都是正确的?或者每个都有它的属性和用法?

java spring dependency-injection

26
推荐指数
1
解决办法
6万
查看次数

如何在Spring Security上从CustomUser获取用户ID

使用Spring Security,我试图从我的CustomUserDetailsS​​ervice上的loadUserByUsername方法返回我的CustomUser实例中的用户id,就像我获取带有Authentication的Name(get.Name())一样.谢谢你的任何提示!

这是我获取已登录用户的当前名称的方式:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String name = authentication.getName();
Run Code Online (Sandbox Code Playgroud)

这是CustomUser

public class CustomUser extends User {

    private final int userID;

    public CustomUser(String username, String password, boolean enabled, boolean accountNonExpired,
                      boolean credentialsNonExpired,
                      boolean accountNonLocked,
                      Collection<? extends GrantedAuthority> authorities, int userID) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        this.userID = userID;
    }
}
Run Code Online (Sandbox Code Playgroud)

和我的服务上的loadUserByUsername方法

@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

    Usuario u = usuarioDAO.getUsuario(s);

    return new CustomUser(u.getLogin(), u.getSenha(), u.isAtivo(), u.isContaNaoExpirada(), u.isContaNaoExpirada(),
            u.isCredencialNaoExpirada(), getAuthorities(u.getRegraByRegraId().getId()),u.getId()
    );
}
Run Code Online (Sandbox Code Playgroud)

java authentication spring spring-security

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

覆盖使用EntityGraph注释的Spring-Data-JPA默认方法会导致QueryException

我正在尝试用Data-JPA实现一个EntityGraph,因为使用QueryDslPredicateExecutor<T>暴露方法findAll(Predicate, Pageable)我需要的那个,我试图覆盖它注释@EntityGraph然后麻烦开始它抛出:

org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=appointment,role=com.physioclinic.entity.Appointment.createdBy,tableName=user,tableAlias=user5_,origin=appointment appointmen0_,columns={appointmen0_.createdBy_id ,className=com.physioclinic.entity.User}}] [select count(appointment)
from com.physioclinic.entity.Appointment appointment where lower(concat(concat(appointment.patient.person.name,?1),appointment.patient.person.surname)) like ?2 escape '!']; nested exception is java.lang.IllegalArgumentException: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=appointment,role=com.physioclinic.entity.Appointment.createdBy,tableName=user,tableAlias=user5_,origin=appointment appointmen0_,columns={appointmen0_.createdBy_id ,className=com.physioclinic.entity.User}}] …
Run Code Online (Sandbox Code Playgroud)

querydsl spring-data-jpa

6
推荐指数
1
解决办法
2794
查看次数

如何使用Social Providers成功登录后设置重定向URL

当我的用户使用一些Spring社交提供商(例如Twitter)成功登录时,我需要更改重定向URL.

我进入每一组***Url("")一个空指针异常有时设置它也不起作用

我到目前为止尝试设置:

public ProviderSignInController signInController(ConnectionFactoryLocator connectionFactoryLocator,
                                                     UsersConnectionRepository usersConnectionRepository) {
        ProviderSignInController providerSignInController = new ProviderSignInController(connectionFactoryLocator,
                usersConnectionRepository,
                new CSignInAdapter(requestCache()));
        providerSignInController.setPostSignInUrl("/home");
        providerSignInController.setApplicationUrl("localhost:8080/home");
        return  providerSignInController;
    }
Run Code Online (Sandbox Code Playgroud)

我分别尝试了setPostSignInUrl和setApplicationUrl中的每一个.

还尝试过:

@Bean
    public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator,
                                               ConnectionRepository connectionRepository) {
        ConnectController connectController = new ConnectController(connectionFactoryLocator, connectionRepository);
        connectController.addInterceptor(new TweetAfterConnectInterceptor());
        connectController.setApplicationUrl("/home");
        return connectController;
    }
Run Code Online (Sandbox Code Playgroud)

我正在使用Spring Social showcase和Security作为基础来做到这一点.如果需要,我发布HttpSecurity配置:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin()
                .loginPage("/signin")
                .loginProcessingUrl("/signin/authenticate")
                .failureUrl("/signin?param.error=bad_credentials")
                .defaultSuccessUrl("/home")
                .and()
                .csrf()
                .and()
                .logout()
                .logoutUrl("/signout")
                .deleteCookies("JSESSIONID")
                .and()
                .authorizeRequests()
                .antMatchers("/admin/**", "/favicon.ico", "/resources/**", "/auth/**", "/signin/**", "/signup/**",
                        "/disconnect/facebook").permitAll()
                .antMatchers("/**").authenticated()
                .and()
                .rememberMe() …
Run Code Online (Sandbox Code Playgroud)

spring spring-social

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

使用OAuth2RestTemplate进行Spring Cloud Feign

我正在尝试实现Feign Clients从用户的服务获取我的用户信息,目前我正在请求oAuth2RestTemplate,它可以工作.但是现在我想改为Feign,但是我得到错误代码401可能是因为它没有携带用户令牌,所以有一种方法可以自定义,如果Spring支持Feign正在使用,那么我可以使用RestTemplate我自己的豆?

今天我正以这种方式实施

服务客户端

@Retryable({RestClientException.class, TimeoutException.class, InterruptedException.class})
@HystrixCommand(fallbackMethod = "getFallback")
public Promise<ResponseEntity<UserProtos.User>> get() {
    logger.debug("Requiring discovery of user");
    Promise<ResponseEntity<UserProtos.User>> promise = Broadcaster.<ResponseEntity<UserProtos.User>>create(reactorEnv, DISPATCHER)
            .observe(Promises::success)
            .observeError(Exception.class, (o, e) -> Promises.error(reactorEnv, ERROR_DISPATCHER, e))
            .filter(entity -> entity.getStatusCode().is2xxSuccessful())
            .next();
    promise.onNext(this.client.getUserInfo());
    return promise;

}
Run Code Online (Sandbox Code Playgroud)

和客户

@FeignClient("account")
public interface UserInfoClient {

    @RequestMapping(value = "/uaa/user",consumes = MediaTypes.PROTOBUF,method = RequestMethod.GET)
    ResponseEntity<UserProtos.User> getUserInfo();
}
Run Code Online (Sandbox Code Playgroud)

spring-security-oauth2 spring-cloud

5
推荐指数
2
解决办法
6965
查看次数

如何在Ember组件上获取单击的元素

我正在学习EmberJS,我试图搜索文档和内容,但到目前为止我无法正确实现组件和响应点击事件的动作,现在它只是在控制台中打印一些东西.我想获得点击的元素,这样我就可以改变它的风格和属性.我正在使用ember-cli 版本0.2.7生成的脚手架.遵循以下代码:

app/components/heart-like.js

import Ember from 'ember';

export default Ember.Component.extend({
  actions:{
    click: function (event) {
      console.log(event); // undefined
      console.log("Hello from component");
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

app/templates/components/heart-like.hbs

 <div class="row">
      <span {{action "click"}} class="pull-right" style="color: #B71C1C;"><i class="fa fa-2x fa-heart"></i></span>
</div>
Run Code Online (Sandbox Code Playgroud)

ember.js ember-cli

2
推荐指数
1
解决办法
5197
查看次数

如何向Spring Cloud Bootstrap添加功能

我想在加载Spring上下文之前添加一些查找,理想情况是在Spring Cloud的引导阶段(当它查找Configuration Server,云连接器等时).如何让我的代码在该阶段执行?

我想要做的是查询Vault以获取我的所有数据库机密和api密钥并设置属性,我知道我可以使用Spring Cloud Config加密,但我喜欢强大的Vault框.(与我可以处理的Vault部分集成)

spring-cloud

2
推荐指数
1
解决办法
2196
查看次数