小编K. *_*ddy的帖子

逐包特征方法是否良好?

最近我在按功能打包java代码时遇到了这个javalobby帖子http://java.dzone.com/articles/how-changing-java-package.

我喜欢这个想法,但我对这种方法的问题很少.我问了我的问题,但没有得到满意的答复.我希望StackOverflow上的某个人可以澄清我的问题.

我喜欢逐个功能的想法,它可以大大减少编码时移动包的时间,所有相关的东西都在一个地方(包).但是不同包中的服务之间的交互呢?

假设我们正在构建一个博客应用程序,我们将所有与用户相关的操作(控制器/服务/存储库)放在com.mycompany.myblog.users包中.并且包中的所有博客相关操作(控制器/服务/存储库)com.mycompany.myblog.posts.

现在我想显示用户个人资料以及他发布的所有帖子.我应该叫myblog.posts.PostsService.getPostsByUser(userId)myblog.users.UserController.showUserProfile()

包之间的耦合怎么样?

无论我在哪里阅读有关逐个功能的内容,每个人都说这是一个很好的做法.那么为什么许多书籍作者甚至框架都鼓励按层分组呢?只是好奇知道:-)

java spring java-ee package-design

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

如何使用<sec:authorize access ="hasRole('ROLES)">来检查多个角色?

我想基于使用Spring Security JSP标记库的角色有条件地显示一些内容.但在Spring Security 3.1.x中只检查一个角色.

我可以使用,但ifAllGranted已被弃用.

有帮助吗?

java spring spring-mvc spring-security

43
推荐指数
2
解决办法
10万
查看次数

如何使用Google Guava自动刷新缓存?

我正在使用Google Guava库进行缓存.对于自动缓存刷新,我们可以执行以下操作:

cache = CacheBuilder.newBuilder()               
                    .refreshAfterWrite(15, TimeUnit.MINUTES)
                    .maximumSize(100)
                    .build(....);
Run Code Online (Sandbox Code Playgroud)

但是,当第一个条目的陈旧请求发生时,将执行自动刷新.

有没有办法自动刷新它,即使没有缓存数据的请求?就像每15分钟一样,缓存数据应该从Db中提取并加载它,无论是否有人调用缓存数据.

此外,Guava的缓存到期时间适用于整个缓存.是否可以基于密钥使缓存值失效?像密钥"NOT_SO_FREQ_CHANGE_DATA"的缓存数据每1小时到期一次,密钥"FREQ_CHANGING_DATA"的数据应该每15分钟到期一次?

java caching guava

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

为什么@OneToOne允许重复关联?

我有User和Address类如下:

class User
{
   ...
   ...
   @OneToOne( cascade=CascadeType.ALL)
   @JoinColumn(name="addr_id")
   private Address address;
}

class Address
{
   ...
   ...
   @OneToOne(mappedBy="address")
   private User user;
}
Run Code Online (Sandbox Code Playgroud)

这里我的假设是这个域模型我可以将一个地址与一个用户关联(user.addr_id应该是唯一的).

但是使用这个域模型,我可以创建多个用户并将它们关联到同一个地址.

User u1 = new User();
//set data
Address addr1 = new Address();
//set data
u1.setAddress(addr1);
...
session.save(u1); 
Run Code Online (Sandbox Code Playgroud)

- >这是使用addr_id = 1创建一个地址记录,并在用户表中使用addr_id = 1插入一个用户记录.精细.

再次,

User u2 = new User();
//set data
Address addr1 = (Address) session.load(Address.class, 1);
//set data
u2.setAddress(addr1);
...
session.save(u2);
Run Code Online (Sandbox Code Playgroud)

- >这是创建第二个用户记录并使用addr_id = 1与现有地址相关联,这是不希望的.

我可以使用@OneToOne(..)@ JoinColumn(name ="addr_id",unique = true)来阻止这种情况.但是使用@OneToOne而不是@ManyToOne(..,unique = true)会有什么不同.

@OneToOne本身应该强加"unique = …

jpa one-to-one

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

无法使用@PersistenceContext注入RESOURCE_LOCAL容器管理的EntityManager

我正在使用JBoss AS 7.1.1并能够配置新的JTA数据源并使用它将其连接到我的EJB

@PersistenceContext(unitName="TestPU")
private EntityManager entityManager;
Run Code Online (Sandbox Code Playgroud)

当我尝试使用RESOURCE_LOCAL PersistenceUnit时,我收到的错误是我无法使用@PersistenceContext注入RESOURCE_LOCAL PU.

我已经配置了我的persistence.xml,如下所示:

<persistence-unit name="TestPU" transaction-type="RESOURCE_LOCAL">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <properties>   
    <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/xy"/>
        <property name="javax.persistence.jdbc.user" value="root"/>
        <property name="javax.persistence.jdbc.password" value="blah"/>        
        <property name="hibernate.hbm2ddl.auto" value="update" />       
      </properties> 
</persistence-unit>
Run Code Online (Sandbox Code Playgroud)

在我的DAO中,

@Stateless
public class UserDAO {
    @PersistenceContext(unitName="TestPU")
    private EntityManager entityManager;


}
Run Code Online (Sandbox Code Playgroud)

当我在AS 7.1.1上部署我的应用程序时,我收到以下错误.

JBAS011428: Cannot inject RESOURCE_LOCAL container managed EntityManagers using @PersistenceContext
    at org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor$1.handle(ModuleJndiBindingProcessor.java:169)
    at org.jboss.as.ee.component.ClassDescriptionTraversal.run(ClassDescriptionTraversal.java:54)
    at org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor.processClassConfigurations(ModuleJndiBindingProcessor.java:162)
    at org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor.deploy(ModuleJndiBindingProcessor.java:155)
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
    ... 5 more
Run Code Online (Sandbox Code Playgroud)

使用RESOURCE_LOCAL PU和@PersistenceContext的任何解决方案?

jpa jta java-ee

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

Spring Boot + Spring Data JPA +交易无法正常工作

我使用带有spring-boot-starter-data-jpa的1.2.0版本创建了一个Spring Boot应用程序,我正在使用MySQL.我正确地在application.properties文件中配置了MySQL属性.

我有一个简单的JPA实体,Spring Data JPA Repository和Service如下:

@Entity
class Person
{
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String name;
    //setters & getters
}

@Repository
public interface PersonRepository extends JpaRepository<Person, Integer>{

}


import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
class PersonService
{
    @Autowired PersonRepository personRepository;

    @Transactional
    void save(List<Person> persons){
        for (Person person : persons) {         
            if("xxx".equals(person.getName())){
                throw new RuntimeException("boooom!!!");
            }
            personRepository.save(person);          
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我有以下JUnit测试:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class) …
Run Code Online (Sandbox Code Playgroud)

spring jpa spring-data-jpa spring-boot

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

如何在VSCode编辑器中调试NodeJS(ES6)代码?

我正在尝试从VSCode调试我在ES6中编写的nodejs应用程序.但它抛出以下错误:

node --debug-brk=18712 --nolazy index.js 
Debugger listening on [::]:18712
/Users/rsiva/Projects/Siva/ntask/ntask-api/index.js:1
(function (exports, require, module, __filename, __dirname) { import express from "express";
                                                              ^^^^^^
SyntaxError: Unexpected token import
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Timeout.Module.runMain [as _onTimeout] (module.js:604:10)
    at ontimeout (timers.js:365:14)
    at tryOnTimeout (timers.js:237:5)
    at Timer.listOnTimeout (timers.js:207:5)
Run Code Online (Sandbox Code Playgroud)

我看过如何在VS Code中调试vue js应用程序?https://medium.com/@katopz/how-to-debug-es6-nodejs-with-vscode-8d00bd6c4f94#.yaevayjs3但这些解决方案无效.

我的package.json:

{
  "name": "ntask-api",
  "version": "1.0.0",
  "description": "Task list API",
  "main": "index.js",
  "scripts": {
    "start": …
Run Code Online (Sandbox Code Playgroud)

javascript babel node.js visual-studio-code

10
推荐指数
1
解决办法
7672
查看次数

带有 Keycloak 的 SpringBoot OAuth2 不返回映射角色作为权限

我正在创建一个简单的 SpringBoot 应用程序并尝试与 OAuth 2.0 提供程序 Keycloak 集成。我在领域级别创建了领域、客户端、角色(成员、PremiumMember),最后创建了用户并分配了角色(成员、PremiumMember)。

如果我使用 Keycloak https://www.keycloak.org/docs/latest/securing_apps/index.html#_spring_boot_adapter提供的 SpringBoot 适配器,那么当我成功登录并检查登录用户的权限时,我可以看到分配的角色例如会员、高级会员。

Collection<? extends GrantedAuthority> authorities = 
 SecurityContextHolder.getContext().getAuthentication().getAuthorities();
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用通用 SpringBoot Auth2 客户端配置,我可以登录,但是当我检查权限时,它总是仅显示ROLE_USER、SCOPE_email、SCOPE_openid、SCOPE_profile ,并且不包括我映射的角色(Member、PremiumMember)。

我的 SpringBoot OAuth2 配置:

pom.xml

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

应用程序属性

spring.security.oauth2.client.provider.spring-boot-thymeleaf-client.issuer-uri=http://localhost:8181/auth/realms/myrealm

spring.security.oauth2.client.registration.spring-boot-thymeleaf-client.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.spring-boot-thymeleaf-client.client-id=spring-boot-app
spring.security.oauth2.client.registration.spring-boot-thymeleaf-client.client-secret=XXXXXXXXXXXXXX
spring.security.oauth2.client.registration.spring-boot-thymeleaf-client.scope=openid,profile,roles
spring.security.oauth2.client.registration.spring-boot-thymeleaf-client.redirect-uri=http://localhost:8080/login/oauth2/code/spring-boot-app
Run Code Online (Sandbox Code Playgroud)

我正在使用SpringBoot 2.5.5Keycloak 15.0.2

使用这种通用的 OAuth2.0 配置方法(不使用 Keycloak SpringBootAdapter)有没有办法获取分配的角色?

java oauth-2.0 spring-boot keycloak

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

如何在RESTEasy中使用通用模板(<T>)从类生成XML响应?

我有一个通用的ServiceResponse类,如下所示:

@XMLRootElement
public class ServiceResponse<T>
{
    private T data;
    private String error;
    //setters n getters

}
Run Code Online (Sandbox Code Playgroud)

从我的RESTEasy服务,我想生成xml响应为:

List<Customer> customers = someDAO.getCustomers();
ServiceResponse<List<Customer>> resp = new ServiceResponse<List<Customer>>();
resp.setData(customers);
resp.setError("No Error");
return resp;
or return Response.ok().entity(resp).build();
Run Code Online (Sandbox Code Playgroud)

但这是抛出错误,因为java.util.List没有JaxbMarshallWriter.

我可以列出usinig GenericEntity类.

GenericEntity<List<Customer>> entity = new GenericEntity<List<Customer>>(customers){};
Response.ok(entity).build();
Run Code Online (Sandbox Code Playgroud)

但是GenericEntity<ServiceResponse<List<Customer>>>没有说java.util.List没有JaxbMarshallWriter.

是否有任何工作可以使用通用模板(,)来编组/解组类?

java rest web-services jaxb resteasy

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

SpringBoot当文件上载大小限制超过获取MultipartException而不是MaxUploadSizeExceededException时

我有简单的SpringBoot应用程序文件上传功能,其中最大文件上传文件大小为2 MB.

我已经配置multipart.max-file-size=2MB它工作正常.但是当我尝试上传大小超过2 MB的文件时,我想处理该错误并显示错误消息.

为此我有我的控制器实现HandlerExceptionResolverresolveException()实现如下:

public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception exception)
    {        
        Map<String, Object> model = new HashMap<String, Object>();
        if (exception instanceof MaxUploadSizeExceededException)
        {
            model.put("msg", exception.getMessage());
        } else
        {
            model.put("msg", "Unexpected error: " + exception.getMessage());
        }

        return new ModelAndView("homepage", model);
    }
Run Code Online (Sandbox Code Playgroud)

问题是我得到的异常是MultipartException而不是MaxUploadSizeExceededException.

stacktrace是: 无法解析多部分servlet请求; 嵌套异常是java.lang.IllegalStateException:org.apache.tomcat.util.http.fileupload.FileUploadBase $ FileSizeLimitExceededException:字段myFile超过其允许的最大大小2097152字节.

在文件大小超过的情况下为什么我没有得到MaxUploadSizeExceededException?我得到它的父Exception MultipartException,除了文件大小超出之外,还可能由于许多其他原因而发生.

有什么想法吗?

java spring-mvc spring-boot

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