w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Spring - @Primary fails against @ComponentScan?
The reason is that both beans actually have the same name foo, so internally one bean definition is getting overridden with the other one, essentially the one with @Bean is getting overridden by the one being scanned by @ComponentScan. The fix is simply to give one of them a different name and you should see the correct behavior of the @Primary bean getting injected. @Primary @Bean public Foo foo1() { return new Foo("Primary bean!!"); } OR @Component("foo1") public class Foo { ..

Categories : Java

Spring: Properly setup @ComponentScan
May be you could try using the base packages of your classes (RMI, Controller): @ComponentScan(basePackages = {"your controller package", "your rmi package"}) If the RMI classes package is different than controller then they will fail to instantiate by spring.

Categories : Spring

Spring: How to use annotation as a parameter to another annotation?
For those annotation attributes that support SpEL it is documented in the API documentation and in such cases you can simply add the SpEL directly instead of wrapping it in another @Value annotation. Unfortunatly the value attribute of the @CacheEvict annotation doesn't support SpEL expressions and as such can only directly contain the names of the caches to evict.

Categories : Java

Inconvenient of @Value Annotation in Spring 3.0
You are right that the annotation configuration can not be instance specific. It is important to understand the concept of bean definitions in bean factory. Manual bean definition: Single <bean> element in your XML config leads to a single bean definition. Multiple <bean> mean multiple definitions (regardless of a bean type). Single @Bean method within @Configuration class leads to a single bean definition. Multiple @Bean methods mean multiple definitions (regardless of a bean type). However when using component scan, classes annotated with @Component-like annotations are auto-registered as a single bean definition. There is no way you can register bean multiple times via component scan. Similarly, annotation configurations (@Value, @Autowired, etc.) are type-wide. Your b

Categories : Spring

spring annotation for ParameterMethodNameResolver
I think you could do the following: @Controller @RequestMapping("/customer") public class CustomerController extends MultiActionController{ @RequestMapping(value="{myHtmFile:.*\.htm}", params = "action=add") public ModelAndView add(HttpServletRequest request, HttpServletResponse response, @PathVariable String myHtmFile) throws Exception { return new ModelAndView("CustomerPage", "msg","add() method"); } .... .... } This uses RegEx to match the pattern. The regex may need some work, but that's the general idea. As a bonus, I show how you can assign the variable using the @PathVariable. If you don't want to do that, I think you can just include the regex in the {} and drop the @PathVariable.

Categories : Spring

Spring AOP vs @Transactional annotation
I've wondered this myself. I found a good discussion of this topic on the Spring forum. Below I've summarize my take from the aforementioned link: AOP Transactional Demarcation Benefits: Java code is devoid of transaction configuration which is contained instead outside of the code in configuration files Java code has no direct dependencies on Spring libraries Transaction management is centralized in one place Can apply transactional boundaries to source code you can't easily modify Drawbacks: AOP complexity. It will not be clear from the code alone where transactional boundaries lie and developers may inadvertently break transactions by, for example, modifying method signatures where a pointcut is applied The need to touch two locations (source code and AOP configuration) in ord

Categories : Spring

@Named annotation in Spring MVC
@Named works the same as @Component. However, the annotations @Controller, @Service, and @Repository are more specific. From the Spring docs: @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively. For example, these stereotype annotations make ideal targets for pointcuts. It is also possible that @Repository, @Service, and @Controller may carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repositor

Categories : Java

setting annotation attributes in spring xml
Yeah -- that's not ever going to work. @LogExecTime(logTime=@Value("#{ConfigureAnnotation.doLogging}")) will never even compile. Annotations are not executable code, they're just markers -- extra bit of information that are inserted into the class file whole sale. You could either put this: @Value("#{ConfigureAnnotation.doLogging}") boolean logTime = true; As a real field on a spring managed bean somewhere, or have change your annotation to be like: @Component @Retention(RetentionPolicy.RUNTIME) public @interface LogExecTime { public String logTime() default "true"; } and have whatever is processing that annotation at run time also accept a spring EL expression and resolve it appropriately, and your component would look like this: @LogExecTime(logTime = "#{ConfigureAnnota

Categories : Java

Which have more priority: Spring annotation or xml configuration
According to this posting, you can't combine "component-scan" and XML-based wiring for the same classes. It seems to say that you will end up instantiating the beans twice.

Categories : Xml

Spring AOP inherited annotation from an interface
@Inhereted annotation can be inherited only by classed and interfaces themselves, not their methods. That is if you annotated UserService with @Privilege annotation then UserServiceImpl would inherited it.

Categories : Java

Custom annotation with spring security
It is not a direct response to your question. As a workoround you can continue to use built-in annotations: @PreAuthorize("hasPermission('USER_MANAGEMENT_READ')") @PreAuthorize("hasPermission('USER_MANAGEMENT_CREATE')") @PreAuthorize("hasPermission('USER_MANAGEMENT_UPDATE')") @PreAuthorize("hasPermission('USER_MANAGEMENT_DELETE')") @PreAuthorize("hasPermission('ORDER_MANAGEMENT_READ')") @PreAuthorize("hasPermission('ORDER_MANAGEMENT_CREATE')") @PreAuthorize("hasPermission('ORDER_MANAGEMENT_UPDATE')") @PreAuthorize("hasPermission('ORDER_MANAGEMENT_DELETE')")

Categories : Spring

Spring AOP not working on all annotation methods
With Spring AOP, your classes which match the pointcut (where you have placed your @Cached annotation in this specific case) should be Spring beans. So the best guess that I can make is that your utility classes are very likely not Spring beans and that is reason why they are not getting woven in. You have two options that I can think of: Make your utility classes also clean Spring beans Use full Aspectj support - this way even though your utility classes are not Spring beans they would be woven with the advice.

Categories : Spring

Clarification on using autowire annotation in spring
No... the component scanning will detect all @Component related beans (including `@Service, @Repository, @Controller etc.). So no you don't need to explicitly define the beans, as that would defy the need for component-scanning and automatic wiring.

Categories : Spring

In Spring 3.2, should we use @Transactional annotation for db activities?
@Transactional is used for making a java code call in transaction so that in case any exception occurred during the process then all database changes will be rolled back. In ideal scenario every service which you think should be independent should have @Transactional annotation. Hibernate also want each database calls in transaction thats why they have implemented in such a way that Transaction will be required for each database query to be successful. I am not sure why you wanted your service to be out of transaction still they would like to fire database calls.

Categories : Spring

Use Spring annotation to inject dependency
@Inject and @Autowired do the same thing, it autowires by type. @Inject is preferred because it is a java annotation and does not couple you to Spring @Resource autowires by name. This is useful when you have many beans of the same type. You can also use @Named along with @Inject for the same behavior.

Categories : Spring

How can I set active profile via annotation in spring?
If you are using making a standalone application or web application you pass active profile these way, according to Spring blog Activation in Web application <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>spring.profiles.active</param-name> <param-value>production</param-value> </init-param> </servlet> Activation with manually created context GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.getEnvironment().setActiveProfiles("dev"); ctx.load("classpath:/com/bank/config/xml/*-config.xml"); ctx.refresh();

Categories : Java

how to get data from spring controller without annotation
It is bit convoluted as with Spring 3, you should ideally be using ResponseBody annotation. Have a look at this class ResponseEntity , this may be useful for your purpose. Sample code from Spring doc : @RequestMapping("/handle") public ResponseEntity<String> handle() { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("MyResponseHeader", "MyValue"); return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED); }

Categories : Java

Spring MVC @Cacheable annotation on Generic Method
First of all think about the implications of using Generics for a moment: You don't know which types you will use in the future. You don't know the cache names either for that matter. You (may) have no type information, so there is no chance of choosing a specific cache. The last point can be solved by always providing type information, like entityClass in your method. Solution 1: One cache Use one cache and generate a key based on the type. @Cacheable(value="myCache", key="#entityClass.name + #id") Solution 2: Use @Caching While you can use expressions for the key you can't use them for the cache names. @Caching allows you to use multiple @Cachable annotations, each with another cache name. @Caching ( @Cacheable(value="books", key="#id", condition="#entityClass.name == 'Book'"),

Categories : Spring

Error importing Spring Context Annotation
The message says it all : The import org.springframework.stereotype.Controller conflicts with a type defined in the same file You have defined a single type in your file: the class Controller, which conflicts with the annotation Controller. @Controller ---> same name ^ | public class Controller { Choose another name, or use the fully qualified name of the enum: @org.springframework.stereotype.Controller public class Controller {

Categories : Java

Spring RequestMapping parameter custom annotation
Use HandlerMethodArgumentResolver (or WebArgumentResolver for versions below 3.1). To enable your argument resolver: If you use @EnableWebMvc - make your @Configuration implement WebMvcConfigurer and override addArgumentResolvers() If you use <mvc:annotation-driver> - use argument-resolvers attribute For older versions you may need to declare AnnotationMethodHandlerAdapter manually and set its customArgumentResolvers

Categories : Spring

Custom annotation binding in Spring Controller
Yes, you can. Spring uses the HandlerMethodArgumentResolver (you can see the default ones in the All Known Implementing Classes area of the javadoc) interface to decide what to pass into your controller method. You can create and register your own HandlerMethodArgumentResolver to find your annotation. public class MyHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { public boolean supportsParameter(MethodParameter parameter) { return parameter.getParameterAnnotation(MyAnnotation.class) != null; } public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Except

Categories : Java

Limiting custom annotation for Spring application
I don't think it is possible to alter the behaviour of @Autowired annotation. However you can easily implement your own BeanPostProcessor and use all the convenience Spring classes, such as AnnotationUtils, ReflectionUtils, etc. On one project we needed custom JAX-WS port injection. So we created @InjectedPort annotation and implemented our own InjectedPortAnnotationBeanPostProcessor (this just illustrates the simplicity of custom injection logic, the purpose of the code itself is unrelated to the question): @Override public Object postProcessBeforeInitialization(final Object bean, String beanName) { // Walk through class fields and check InjectedPort annotation presence ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { @Override public void d

Categories : Spring

Spring @Query annotation with enum parameter
I suggest proper use of JPA enumerated types. Change the type "role" property as: @Column(name = "role") @Enumerated(EnumType.STRING) private Roles role; This should automatically fix the query result.

Categories : Java

@Resource annotation picked up both by spring and app server
For Point 1: You can try adding a metadata-complete="true" attribute to the webapp element in your web.xml file, this should prevent scanning and resolution of @Resource annotations by the container. For Point 2, 3: Implementing a Spring Factory Bean may be a better option, this way you can specify the exact type to expect using the getObjectType() api.

Categories : Java

Spring Autowire Annotation with Several Interface Implementations
You can inject all implentations as List: @Autowired List<A> as; or as Map with bean name as key: @Autowired Map<String, A> as; and then choose proper implementation manually (perhaps, in a setter method): @Autowired public void setAs(Map<String, A> as) { this.a = ...; }

Categories : Java

Spring @Transaction annotation and Exception Handling
I have solved this issue by designing around the problem. Sending an Email was never meant to be part of the transaction. I created an object that performed post saving tasks. The object will catch the exception thrown upon saving the termination and if no exceptions were thrown I would then trigger an email to be sent out. One could also put this in an Spring Aspect which could be executed upon successfully returning after a successful save. Lessons learn't: Don't include steps that don't belong in a method marked with @transaction. If its included in a transaction Spring will silently handle the exception and not throw the exception till the transaction is finished. In short if a method is annotated with @Transaction every line in that method will be execute even though a line in the m

Categories : Java

Creating multiple pages in spring mvc using annotation
There's loads of sample projects that already do this that Spring offer on github. Take a look at their repository here So all you want is to click a button, this fires off to a spring endpoint that returns a view.

Categories : Jsp

Looking for a solution to extend Spring MVC with another Component/Annotation
HandlerInterceptor can be used to intercept the RequestMapping handling. This is a simple example how to configure and implement one. You can check for your session variable and will have a bunch of methods that will allow you to do custom processing or just exchange the view from the normal controller handling with your mobile view.

Categories : Spring

Spring: Apply Annotation based on properties
My Idea: Use an extra bean (MyScheduler), that contains nothing more than a method annotated with @Schedule. This Method "forward" the invocation to your real Service. Then annotate the MyScheduler class with @Component and @Profile The use your properties file to enable or disable this profile Sketch: @Component @Profile("onTHEserver") public class MyScheduler{ @Autowire private RealService realService; @Schedule(cron="1****") { realService.doSomething(); } } @See: Spring 3.1 M1: Introducing @Profile @See: @Profile Java Doc

Categories : Spring

Is there a way to declare two spring beans instance from the same class with annotation only?
If you need multiple instances of a bean you must explicitly configure them either in XML or in a @Configuration annotated class. Either way you need some way of explicitly defining the beans, you cannot have multiple instances only by component-scanning.

Categories : Java

Dynamically changing the @ResponseStatus in annotation driven Spring MVC
@ResponseStatus(HttpStatus.OK) means that the request will return OK if the handling method returns normally (this annotation is redundant for this case, as the default response status is HttpStatus.OK). If the handler throws an exception, the annotation does not apply. How can I handle multiple response statuses depending on conditions in the same method? That question has already been asked. Can I change the Response Status on occurrence of any exception You have two choices. If the exception class is one of your own, you could annotate the exception class with @ResponseStatus. The other choice is to provide the controller class with an exception handler, annotated with @ExceptionHandler, and have the exception handler set the response status.

Categories : Spring

Spring AOP, pointcut expressions : annotation with specific param
I think you are quite close. In your clear method, you should take in a parameter of type JoinPoint. This parameter will be auto populated by Spring at runtime, and with it, you can get details of your specific joinpoint, including the java.lang.reflect.Method, which will contain the annotation you are after. I am thinking something like this: @Aspect public class Clear { @After("@annotation(org.springframework.transaction.annotation.Transactional)") public void clear(final JoinPoint joinPoint) { final Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); final Transactional txAnnotation = methood.getAnnotation(Transactional.class); final boolean isReadOnly = txAnnotation.readOnly(); //do conditional work based on isReadOnl

Categories : Java

How Do I Use Spring Data HBase With Annotation Driven Config
// <hdp:hbase-configuration/> @Bean public Configuration configuration() { return HBaseConfiguration.create(); } // <bean id="htemplate" class="org.springframework.data.hadoop.hbase.HbaseTemplate" p:configuration-ref="hbaseConfiguration"/> @Bean(name = "hbaseTemplate") public HbaseTemplate hbaseTemplate() { return new HbaseTemplate(configuration()); }

Categories : Spring

Handling all listed exceptions but one with Spring's @ExceptionHandler annotation
I don't think there is a way to do that with the @ExceptionHandler annotation. One approach that should work is for you to provide an implementation of the HandlerExceptionResolver interface. In your implementation you could provide the code from your @ExceptionHandler methods and only execute it for the Exceptions that you wish to handle. I think for Spring MVC to pick-up your custom HandlerExceptionResolver, it will just need to be registered as a bean within your ApplicationContext.

Categories : Spring

Is there a way to use constants inside Spring Data @Query annotation value?
I would recommend creating an Enum and a field of that enum on the entity. public enum UserModelStatus{ ACTIVE, INACTIVE } public UserModel{ /* Other fields ommitted */ @Enumerated(EnumType.STRING) private UserModelStatus status; /* Get/Set Method */ } Then create your repository method: @Repository public interface UserModelRepository extends JpaRepository<UserModel, Long>{ public List<UserModel> findByStatus(UserModelStatus status); } Using Spring Data you won't even need to write JPQL just call the method like: @Autowired UserModelRepository userModelRepository; public void someMethod(){ List<UserModel> userModels = userModelRepository.findByStatus(UserModelStatus.ACTIVE); }

Categories : Java

How to override a Spring @Autowire annotation and set a field to null?
These could help: Context configuration with annotated classes Testing with @Configuration Classes and Profiles Spring TestContext Framework and profiles: beans profile="..." Introducing @Profile You could create different beans definition in the XML configuration and then activate them using the -Dspring.profiles.active="profile1,profile2" env.

Categories : Spring

spring 3.2 configuration tx:annotation-driven error in eclipse
Incomprehensible glitch with Eclipse/Java/PC. Only answer I have is: Leave the computer on overnight without touching it and it'll fix itself. Maybe, rebooting after taking the battery out would result in the same. I can only suspect that some garbage collection happened, which cleared up a corruption in Java and/or Eclipse.

Categories : Spring

Spring MVC custom validation annotation with service @Autowired
The solution was finally to disable the JPA validation because it was used instead of the Hibernate validation, so the Spring injection wasn't effective. So I just add in my JPA configuration this : <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> ... <property name="jpaPropertyMap"> <map> <entry key="javax.persistence.validation.mode" value="NONE"/> </map> </property> </bean>

Categories : Spring

Using Interceptor with Annotation in Struts2 with Spring and Convention Plugin
By default the Convention plugin uses its own package convention-default which doesn't contain your package defined in struts.xml. To change that you have two options, both described in the docs [1]: use @ParentPackage annotation or define <constant name="struts.convention.default.parent.package" value="default"/> in struts.xml [1] http://struts.apache.org/development/2.x/docs/convention-plugin.html#ConventionPlugin-ParentPackageannotation

Categories : Spring

why transaction management using annotation is failing in spring with the below configuration
Because you catched the exception. Remove the try catch or rethrow the exception: try{ ... } catch (RuntimeException e) { e.printStackTrace(); System.out.println("transaction rolled back"); throw e; //rethrow so spring will recognize it }

Categories : Spring



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.