标签: spring-annotations

我不能将 @Value 注释与 @Transient 注释一起使用吗?

我有一个类来映射一个使用休眠的表。有一些变量我想忽略以用于映射以用作常量。我想从属性加载常量值,所以我这样编码:

@Transient
@Value("${something.value}")
private int MY_VALUE;
Run Code Online (Sandbox Code Playgroud)

但是,的值MY_VALUE始终设置为 0。我不能将 @Transient 注释与 @Value 注释一起使用吗?还是我错过了其他东西?

java spring hibernate spring-annotations hibernate-annotations

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

将@value与PropertyPlaceholderConfigurer一起使用

我有属性文件report.properties(\ WEB-INF\classes\properties\report.properties),带有条目:

reportTemplate = reports/report5.jrxml
Run Code Online (Sandbox Code Playgroud)

applicationContext-reports.xml(\ WEB-INF\config\applicationContext-reports.xml)以及条目:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:properties/report.properties"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

web.xml:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/config/applicationContext-reports.xml
    </param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)

在我的控制器中我有:

private @Value("${reportTemplate}") String reportTemplatePath;
Run Code Online (Sandbox Code Playgroud)

但是当我打印这个以检查它的价值时:

System.out.println("reportTemplatePath="+reportTemplatePath);
Run Code Online (Sandbox Code Playgroud)

而不是输出:( reports/report5.jrxml取自属性文件)它给出reportTemplatePath=${reportTemplate}

编辑:在此处复制OP评论以获得清晰度并显示其System.out.println位置.

@Controller
public class myController {
    private @Value("${reportTemplate}") String reportTemplatePath;
    // other field declarations... 

    @RequestMapping(value="report.htm", method=RequestMethod.GET) public String showReport() throws JRException{
        ...
        System.out.println("reportTemplatePath="+reportTemplatePath);
        ...
        return "report";
    }
}
Run Code Online (Sandbox Code Playgroud)

spring spring-annotations

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

Spring Security + MVC annotations非法参数异常

我正在使用spring MVC和spring security.

我有注释驱动的控制器,并尝试添加安全注释.

控制器代码:

@Controller
public class SomeController implements MessageSourceAware {

    @Secured("ROLE_ADMIN")
    @RequestMapping(value = "/somepage", method = RequestMethod.GET)
    public String getPage(HttpServletRequest request, ModelMap model) {
        // logic
        return ADMIN_VIEW_NAME;
    }
Run Code Online (Sandbox Code Playgroud)

我的spring-security.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/security
       http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <security:global-method-security secured-annotations="enabled" />

    <security:http auto-config="true" use-expressions="true" access-denied-page="/denied">

        <security:intercept-url pattern="/login" access="permitAll"/>
        <!--<security:intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')"/>-->

        <security:form-login
                login-page="/login"
                authentication-failure-url="/login?error=true"
                default-target-url="/index"/>

        <security:logout
                invalidate-session="true"
                logout-success-url="/login"
                logout-url="/logout"/>

    </security:http>

    <!-- Declare an authentication-manager to use a custom userDetailsService -->
    <security:authentication-manager>
        <security:authentication-provider …
Run Code Online (Sandbox Code Playgroud)

spring-mvc spring-security spring-annotations

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

为什么更改joinColumn的顺序,hibernate返回正确或不正确的查询?

问题:

为什么更改joinColumn的顺序,hibernate返回正确或不正确的查询?

第一次加入:

@OneToOne
      @JoinTable(name="TTR_POA_UPA",
        joinColumns = {
          @JoinColumn(name="ANO", insertable=false, updatable=false),
          @JoinColumn(name="ID_ESCALA", insertable=false, updatable=false),
          @JoinColumn(name="MES", insertable=false, updatable=false)          
        },
        inverseJoinColumns = {
          @JoinColumn(name="ANO", insertable=false, updatable=false),
          @JoinColumn(name="ID_ESCALA", insertable=false, updatable=false),
          @JoinColumn(name="MES", insertable=false, updatable=false)
        }     
      )
private PoaUpa poaUpa;
Run Code Online (Sandbox Code Playgroud)

返回:

Hibernate: select * from ( select autorizaci0_.ano as ano0_, autorizaci0_.ID_ESCALA as ID2_0_, autorizaci0_.mes as mes0_, autorizaci0_.AUTORIZACION_HORAS_DIA_FIJIS as AUTORIZA4_0_, autorizaci0_.AUTORIZACION_HORAS_EVENT as AUTORIZA5_0_, autorizaci0_.AUTORIZACION_HORAS_FACTP as AUTORIZA6_0_, autorizaci0_.AUTORIZACION_HORAS_FIJIS as AUTORIZA7_0_, autorizaci0_.AUTORIZACION_HORAS_FIJOS as AUTORIZA8_0_, autorizaci0_.AUTORIZACION_HORAS_SEM_FACTP as AUTORIZA9_0_, autorizaci0_.AUTORIZACION_NAP as AUTORIZ10_0_, autorizaci0_.AUTORIZACION_NUM_PERS_EVENT as AUTORIZ11_0_, autorizaci0_.AUTORIZACION_OBSERVACIONES as AUTORIZ12_0_, autorizaci0_.PETICION_HORAS_DIA_FIJIS as …
Run Code Online (Sandbox Code Playgroud)

java spring hibernate spring-annotations hibernate-annotations

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

在 Spring 中缓存带有数组参数的方法

我有一个具有多种方法的服务,并尝试使用 Spring@Cacheable注释来缓存它们。一切正常,除非我发现带有数组作为方法参数的方法没有被缓存。考虑到数组可以保存不同的值,这有点有意义,但我仍然认为这是可能的。

缓存了以下方法:

@Cacheable("myCache")
public Collection<Building> findBuildingByCode(String buildingCode) {...}

@Cacheable("myCache")
public Collection<Building> getBuildings() {...}
Run Code Online (Sandbox Code Playgroud)

但是,如果我将findBuildingByCode方法更改为以下任一方法,则不会缓存它:

@Cacheable("myCache") 
public Collection<Building> findBuildingByCode(String[] buildingCode) {...}

@Cacheable("myCache")
public Collection<Building> findBuildingByCode(String... buildingCode) {...}
Run Code Online (Sandbox Code Playgroud)

这是相关的Spring xml配置:

<!-- Cache beans -->
<cache:annotation-driven/>

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
    p:cache-manager-ref="ehcache" />

<!-- EhCache library setup -->
<bean id="ehcache"
    class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />
Run Code Online (Sandbox Code Playgroud)

ehcache配置:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">

<diskStore path="java.io.tmpdir/ehcache" />

<!-- Default settings -->
<defaultCache eternal="false" maxElementsInMemory="1"
    overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
    timeToLiveSeconds="100" memoryStoreEvictionPolicy="LRU" />

<!-- …
Run Code Online (Sandbox Code Playgroud)

java spring ehcache spring-annotations

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

如何使用注释对Spring执行基于构造函数的依赖注入?

好的,所以如果我需要在构造函数中放入一些原始值,我该怎么做?

    @Autowired
public CustomBean(String name, @Qualifier("SuperBean") SuperBean superBean) {
    super();
    this.superBean = superBean;
    this.name = name;
}
Run Code Online (Sandbox Code Playgroud)

例如,我在这里定义superBean有限定符"SuperBean",但我也想知道如何使用注释在这里设置名称值?

我知道有可能使用xml配置,但我想知道如何使用注释执行此操作:

<bean id="CustomXmlBean" class="org.arturas.summerfav.beans.CustomXmlBean">
        <constructor-arg name="name" type="String" value="The Big Custom XML Bean" />
        <constructor-arg>
            <bean id="SuperBean" class="org.arturas.summerfav.beans.SuperBean" />
        </constructor-arg>
    </bean>
Run Code Online (Sandbox Code Playgroud)

那么我如何为String,int和其他泛型类型输入值?

java spring dependency-injection spring-annotations constructorargument

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

为什么“@Transactional(propagation =propagation.NEVER)”不起作用?

在 Spring 文档中,用于NEVER传播:

以非事务方式执行,如果存在事务则抛出异常。

我想尝试如下:

@Transactional(propagation = Propagation.NEVER)
public void getDeps(long ID) {
    System.out.println(databaseImp.getDepartmentByID(ID));
}

@Transactional(propagation = Propagation.REQUIRED)
public void allProcessOnDB_second(long ID) {
    getDeps(ID);
    operation(ID);
}

@Transactional
public void operation(long id){
    System.out.println(databaseImp.getDepartmentByID(id));
}
Run Code Online (Sandbox Code Playgroud)

好吧,代码想要做什么并不重要。
我使用@Transactional(propagation = Propagation.NEVER)并且我在任何事务方法中使用此方法,但它不起作用。我的意思是它必须抛出异常,但事实并非如此。

我的 Spring 元配置文件 (XML) 包含以下内容:

<context:annotation-config></context:annotation-config>
<context:component-scan base-package="database.transactionmanagement"/>

<tx:annotation-driven transaction-manager="transactionManager" mode="aspectj"/>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <constructor-arg name="dataSource" ref="datasource2"/>
</bean>

<bean id="datasource2" class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost/hr"/>
    <property name="username" value="root"/>
    <property name="password" value=""/>
</bean>
Run Code Online (Sandbox Code Playgroud)

感谢您的回答。

java spring transactions spring-aop spring-annotations

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

BigDecimal 中的 Spring MVC 控制器 NumberFormat 注释模式问题

我有一个采用多个BigDecimalRequestParams的弹簧控制器。

我的应用程序语言环境是 en_US 但只是对于这个控制器方法,我需要BigDecimal在 de_DE 语言环境中绑定和转换这些参数(即#.###,## > DOT 用于分组和 COMMA 用于小数分隔符)。

这些BigDecimal值来自 UI 文本框并且它们已经在de_DE格式中。这是我的控制器代码失败并出现以下错误:

“未能将‘java.lang.String’类型的值转换为所需类型‘java.math.BigDecimal’;嵌套异常为java.lang.NumberFormatException”

@RequestMapping(value = "/create", method = RequestMethod.POST)
public ModelAndView create(@RequestParam("referenceNumber") String referenceNumber, @RequestParam("startDate") @DateTimeFormat(pattern="dd-MM-yyyy") Date startDate, @RequestParam("amount1") @NumberFormat(pattern = "#.###,##") BigDecimal amount1, @RequestParam("amount2") @NumberFormat(pattern = "#.###,##") BigDecimal amount2) {

    // Do something and return

}
Run Code Online (Sandbox Code Playgroud)

Spring 以某种方式忽略了我的数字格式模式。请注意DateTimeFormat注释按预期工作;以正确的形式解析 startDate 参数。

任何帮助,将不胜感激。

谢谢。

java spring spring-mvc spring-annotations numberformatexception

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

Spring的@Bean批注和@Component批注有什么区别?

对您来说这可能是一个非常简单的问题,但是我阅读了许多文档并且感到非常困惑。我们可以使用@Component而不是@Bean或@Bean来代替@Component(以及@Repository @Service @Controller)吗?

干杯

spring spring-annotations spring-boot

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

如何在Spring Boot中创建自定义注释?

我正在做一个春季项目,我想做注释。

我需要类似下面的描述:

@CustomAnnotation("b")
public int a(int value) {
  return value;
}

public int b(int value) {
  return value + 1 ;
}

--------------------------

Execute :

a(1) // should return '2'  
Run Code Online (Sandbox Code Playgroud)

java annotations spring-mvc spring-annotations spring-boot

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