小编chz*_*gla的帖子

Spring security的SecurityContextHolder:会话或请求绑定?

Userprincipal是否从SecurityContextHolder绑定到请求或会话中检索?

UserPrincipal principal = (UserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

这是我访问当前登录用户的方式.如果当前会话被销毁,这会失效吗?

java spring spring-security java-ee

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

第一次使用时,Jodatime的LocalDateTime很慢

我目前正在java项目中测试一些webapp技术,并且想知道为什么页面有时会加载很快,有时需要花费近5秒来加载.

我终于发现它就是这条线

LocalDateTime now = new LocalDateTime();

当它第一次被调用时,需要永远获得当前时间.在那之后调用时,即使是完全不同的地方,它也会非常快.

我正在使用

    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>1.6.2</version>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

有没有人有类似的经历?真的卡在这里..我可以在我的应用程序的早些时候使用LocalDateTime来紧固后续调用 - 但这似乎相当沉闷.

编辑

我现在误用了Spring:

@Service
public class JodaTimeLoader {

  public JodaTimeLoader() {
    LocalDateTime loadMe = new LocalDateTime();
  }

}
Run Code Online (Sandbox Code Playgroud)

java jodatime

17
推荐指数
3
解决办法
2872
查看次数

在基于注释的bean中定义destroy-method?

我正在寻找一种方法来告诉Spring在基于注释的bean上应该调用哪个方法来调用该bean.

我实际想要实现的是,当会话范围的bean被销毁时被通知以便从该会话中持久存储一些东西.

lifecycle spring annotations

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

无法在方法级别覆盖Spring Security的类型级别的@PreAuthorize

我正在尝试使用@PreAuthorize类型级别的注释来保护Controller,并尝试通过使用不同的方法注释某些方法来覆盖该行为@PreAuthorize.然而,问题是,Spring首先评估方法注释(授予访问权限),然后评估类注释(拒绝访问).

有没有办法扭转这种秩序?我还想不出来.

编辑:

在方法级别,我只想授予对非注册用户的访问权限:

@PreAuthorize("isAnonymous()")
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String renderCreateEntity(ModelMap model) {
    return userService.renderCreateEntity(model);
}
Run Code Online (Sandbox Code Playgroud)

但是,此Controller的标准应该是仅允许完全通过身份验证的用户:

@Controller
@RequestMapping(value = "/user")
@PreAuthorize("isFullyAuthenticated()")
public class UserController { [...] }
Run Code Online (Sandbox Code Playgroud)

当通过应用程序调试步进时,我看到isAnonymous()首先评估,然后isFullyAuthenticated()导致授予访问权限并立即再次拒绝访问.

java spring spring-security

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

Glassfish 4.0中的Bean-Validation 1.1 - CDI注入不按预期工作

根据Glassfish 4.0 wiki,Glassfish 4.0应包含JSR349 Bean Validation 1.1: GF4 wiki链接

根据JSR349规范,CDI Injection应该开箱即用:Bean Validation 1.1.CDI集成

所以我相应地更改了我的pom.xml:

<dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
        <scope>provided</scope>
 </dependency>
Run Code Online (Sandbox Code Playgroud)

并尝试将CDI Bean注入ConstraintValidator:

public class UniqueEmaiValidator implements ConstraintValidator<UniqueEmail, String> {

    @Inject
    private UserAccountService accountService;

    @Override
    public void initialize(UniqueEmail constraintAnnotation) {
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
         return !accountService.userExistsByEmail(value);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,在测试应用程序(使用arquillian-glassfish-remote-3.1 1.0.0.CR4运行Arquillian 1.1.1.)时,验证将始终失败,因为它userAccountService为null,因此NullPointerException最终会抛出 .

我错过了什么使Bean Validation 1.1工作?

编辑:

A)可以确认它不是由Arquillian远程测试引起的 - 也会抛出NPEx.在服务器上运行时

B)在GlassFish Server Open Source Edition 4.0上运行(build 89)

C)我使用Hibernate Validator的5.0.1.FINAL显式重新构建了bean-validation.jar.的mvn package输出: …

glassfish java-ee cdi bean-validation

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

如何在Spring 3中将@Aspect与@Controller结合起来?

我正在尝试使用@Controller,基于注释的方法设置Spring 3 Web MVC项目.

package my.package

@Controller
@RequestMapping("/admin/*")
public class AdminMultiActionController {

@RequestMapping(value = "admin.htm", method = RequestMethod.GET)
public String showAdminSection() {
    return "admin";
}
Run Code Online (Sandbox Code Playgroud)

我的dispatcher-servlet具有以下Controller处理程序:

<context:component-scan base-package="my.package" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
Run Code Online (Sandbox Code Playgroud)

使用提供的maven工件,webapp运行良好:

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

现在我想添加@AspectJ AOP.我得到了libs:

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.9</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.9</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

添加到我的applicationContext.xml:

<aop:aspectj-autoproxy/>
Run Code Online (Sandbox Code Playgroud)

确保在applicationContext.xml中创建相关的bean:

<bean id="securityInterceptor" class="my.package.service.SecurityInterceptor"/>
Run Code Online (Sandbox Code Playgroud)

并开始充实@Aspect:

package my.package.service

@Aspect
public class SecurityInterceptor {

@Pointcut("execution(* showAdminSection(..))")// the pointcut expression
private void foo() {
    System.out.println("fooo");
}// the pointcut …
Run Code Online (Sandbox Code Playgroud)

java model-view-controller aop spring aspectj

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

在JUnit Test中的MockHttpServletRequest中设置@ModelAttribute

我正在尝试测试一个弹簧mvc控制器.其中一种方法将表单输入作为POST方法.此方法通过@ModelAttribute注释获取窗体的commandObject .如何使用Spring的Junit测试设置此测试用例?

控制器的方法如下所示:

@RequestMapping(method = RequestMethod.POST)
public String formSubmitted(@ModelAttribute("vote") Vote vote, ModelMap model) { ... }
Run Code Online (Sandbox Code Playgroud)

Vote对象在.jsp中定义:

 <form:form method="POST" commandName="vote" name="newvotingform">
Run Code Online (Sandbox Code Playgroud)

现在我想在Test中测试这个表单POST,其设置如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring/applicationContext.xml"})
@TestExecutionListeners({WebTestExecutionerListener.class, DependencyInjectionTestExecutionListener.class})
public class FlowTest { ... }
Run Code Online (Sandbox Code Playgroud)

测试表单POST的实际方法:

@Test
public void testSingleSession() throws Exception {

    req = new MockHttpServletRequest("GET", "/vote");
    res = new MockHttpServletResponse();
    handle = adapter.handle(req, res, vc);
    model = handle.getModelMap();

    assert ((Vote) model.get("vote")).getName() == null;
    assert ((Vote) model.get("vote")).getState() == Vote.STATE.NEW;

    req = new MockHttpServletRequest("POST", "/vote");
    res = …
Run Code Online (Sandbox Code Playgroud)

junit spring annotations spring-mvc

6
推荐指数
2
解决办法
9021
查看次数

@Scheduled&scheduler:pool-size究竟做了什么?

我想同时运行几个预定的任务.

配置spring时,我可以为调度程序提供池大小:

<task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
<task:executor id="myExecutor" pool-size="32"/>
<task:scheduler id="myScheduler" pool-size="1000"/>
Run Code Online (Sandbox Code Playgroud)

但是游泳池大小到底意味着什么呢?

这是否意味着它只能存储1000个预定方法,还是意味着只能同时处理1000个方法?

tldr; 如果注解的方法一@Scheduled(FIXEDDELAY = 60)不要在此刻执行(这意味着它的延迟之间),它填补了游泳池或不?

java spring annotations scheduling scheduled-tasks

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

@Transactional Spring Junit测试没有做回滚

我尝试为我的dao层设置一个Junit测试用例.但是,我希望测试数据实际上持久保存到DB.

所以我认为我应该在事务上进行并在每次测试后回滚.这让我有以下数据源设置:

<bean id="dataSource"
    class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
    p:driverClass="org.postgresql.Driver"
    p:jdbcUrl="jdbc:postgresql://***"
    p:user="***"
    p:password="***/>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
      p:dataSource-ref="dataSource"
      p:packagesToScan="***"
      p:hibernateProperties-ref="hibernateProps" />

<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
      p:dataSource-ref="dataSource"
      p:sessionFactory-ref="sessionFactory"/>
Run Code Online (Sandbox Code Playgroud)

待测试的dao类设置如下:

@Repository
@Transactional
@SuppressWarnings("unchecked")
public class BallotBoxRepositoryHibernateImpl implements BallotBoxRepository {

@Autowired
private SessionFactory sessionFactory;

  @Override
  public void saveVote(DaoObject v) {
    Session sess = sessionFactory.openSession();
    sess.beginTransaction();
    sess.save(v);
    sess.getTransaction().commit();
    sess.close();
  }
[...]
}
Run Code Online (Sandbox Code Playgroud)

实际的持久工作确实很有效.但是,从未进行过预期的回滚:

INFO main transaction.TransactionalTestExecutionListener:292 - Rolled back transaction after test execution for test context [...]
Run Code Online (Sandbox Code Playgroud)

TransactionalTextExecutionListener定义如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = …
Run Code Online (Sandbox Code Playgroud)

postgresql junit spring hibernate transactional

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

在Junit测试中使用来自WEB-INF的i18n资源

我想我的类路径设置遇到了错误.

我想测试一个国际化的网络应用程序,其中的messagesource定义如下:

<bean id="messageSource"
  class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>/WEB-INF/i18n/errors</value>
            <value>/WEB-INF/i18n/messages</value>
            <value>/WEB-INF/i18n/links</value>
            <value>/WEB-INF/i18n/forms</value>
            <value>/WEB-INF/i18n/communication</value>
        </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

加载这些值在生产环境中完美运行.但是,在运行Junit Test时,它无法解析这些属性文件,因为它们不在类路径中.

但是,我希望它们不在类路径上,因为我可以利用我可以在属性文件中更改内容的功能,并立即反映在网站上: Since application servers typically cache all files loaded from the classpath, it is necessary to store resources somewhere else (for example, in the "WEB-INF" directory of a web app). Otherwise changes of files in the classpath will not be reflected in the application.

spring applicationContext位于那里:/src/main/resources/spring/applicationContext.xml 并使用这些注释加载到Junit测试中:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring/applicationContext.xml"})
Run Code Online (Sandbox Code Playgroud)

如何让Junit获取那些非类路径资源呢?属性文件已打开/src/main/webapp/WEB-INF/i18n/*

Junit:4.7.

春天:3.0.5.

junit spring classpath

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