Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate Spring Bean's File field via Annotation

Is it possible to do something like this :

<property name="template" value="file:/some/resource/path/myTemplate.txt" />

via annotations without creating custom annotation and populate the field via reflection ? It cannot be done with @Value, cause it works only with Strings...

If not, what is the best way to process Spring bean custom annotations and init the bean accordingly ?

like image 657
lisak Avatar asked Jun 17 '11 22:06

lisak


People also ask

How to configure beans in a Spring container?

There are several ways to configure beans in a Spring container. Firstly, we can declare them using XML configuration. We can also declare beans using the @Bean annotation in a configuration class. Finally, we can mark the class with one of the annotations from the org.springframework.stereotype package, and leave the rest to component scanning. 2.

What is @BEAN annotation in Spring JAVA?

In this article, we will discuss Spring Java configuration based @Bean annotation with examples. We will also discuss different scenarios of how and when to use @Bean annotation. @Bean is a method-level annotation and a direct analog of the XML element <bean />.

What is the default name of a bean in an annotation?

By default, the bean instances of this class have the same name as the class name with a lowercase initial. In addition, we can specify a different name using the optional value argument of this annotation. Since @Repository, @Service, @Configuration, and @Controller are all meta-annotations of @Component, they share the same bean naming behavior.

How do I declare a bean in Spring Boot?

To declare a bean, simply annotate a method with the @Bean annotation. You use this method to register a bean definition within an ApplicationContext of the type specified as the method’s return value. By default, the bean name will be the same as the method name . The preceding configuration is exactly equivalent to the following Spring XML:


1 Answers

Use a Resource as the field.

@Value("file:/some/resource/path/myTemplate.txt")
Resource template;

You can use classpath: style URIs this way too.

Then if you need to get a File, use template.getFile()

like image 173
sourcedelica Avatar answered Dec 12 '22 13:12

sourcedelica