javahibernatespringhibernate-annotationsspring-annotations

Can't I use @Value annotation with @Transient annotation?


I have a class to map a table for using hibernate. There are some variable I want to ignore for mapping to use as constant. And I want to load constant value from properties so I code it like this:

@Transient
@Value("${something.value}")
private int MY_VALUE;

But, the value of MY_VALUE is always set to 0. Can't I use @Transient annotation with @Value annotation? Or I missed something else?


Solution

  • You use @Value to specify a property value to load when Spring creates the bean.

    However, if you are using Hibernate to load data from a database, Spring is not instantiating these classes for you. So your @Value annotation has no effect.

    I would suggest injecting the @Value into the DAO that loads these entities from Hibernate, something like

    public class FooDao {
        @Value("...")
        private int yourConfiguredValue;
    
        public getFoo() {
            Foo foo = sessionFactory.getCurrentSession().get(...);
            foo.setYourValue(yourConfiguredValue);
            return foo;
        }
    }