Menu
  • HOME
  • TAGS

Can not understand difference in behavior between : @EnableWebMvc and

java,spring,spring-annotations

Although @EnableWebMvc and <mvc:annotation-driven /> have the same purpose, enabling support for @Controller with @RequestMapping. They aren't complementary either use Java based config or xml, mixing them will not work. The WebMvcConfigurerAdapter or actually the WebMvcConfigurer is only designed and detected when using @EnableWebMvc not when using <mvc:annotation-driven />. When...

Hibernate does not save Object even not getting any error in log

java,hibernate,spring-mvc,hibernate-mapping,spring-annotations

Use this code and test once public void save(Example example) { Session session = null; Transaction tx=null; try { log.info( example.toString()); session = this.sessionFactory.openSession(); tx = session.beginTransaction(); session.persist(example); tx.commit(); } catch (Exception e) { e.printStackTrace(); } finally { if (!tx.wasCommitted()) { tx.rollback(); }//not much doing but a good practice session.flush();...

Sending data from AngularJS factory to a Spring Controller

ajax,angularjs,spring-mvc,spring-annotations

Thy this i modified your controller : @Controller @SessionAttributes("dataObject") public class ScreenDesignerController extends BaseController { /** * Injected screen designer service class. */ @Autowired private ScreenDesigner screendiService; @RequestMapping(value = "FormBuilder", method = RequestMethod.POST) public final String knowDetails(@RequestBody String myJsonStr,@ModelAttribute("globalUser") User globalUser, BindingResult result, RedirectAttributes redirectAttributes, final Model model ) throws...

Get DB column names from annotated bean in java

java,annotations,spring-annotations

You can get list of the class' fields SampleBO.class.getFields() (An array of Field is returned) and go through the array to check whether it has the annotation. See the example If the annotation present you can get value of the annotation's columnName....

@PathVariable and @RequestParam not working together

spring,spring-mvc,annotations,spring-annotations,path-variables

Can you try with below snippet: @RequestMapping(value = "/child/{nodeId}/{relType}",method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON) public Iterable<Node> getConnectedNodes(@RequestParam(value="page", required=false) int page, @RequestParam(value="size", required=false) int size, @PathVariable("nodeId") String nodeId, @PathVariable("relType") String relType) { return nodeService.getConnectedNodes(nodeId, relType,page,size); } ...

Purpose of using permitAll() in PreAuthorize annotation in Spring Security

java,security,spring-security,annotations,spring-annotations

permitAll() does exactly what it says. It allows (permits) any user's (all) session to be authorized to execute that method. The way spring manages its authentication and authorization means that anyone accessing your site is provided with a session. This session can be anonymous, or authenticated (user's provided some kind...

How to inject a Map using the @Value Spring Annotation?

java,spring,dependency-injection,annotations,spring-annotations

I believe Spring Boot supports loading properties maps out of the box with @ConfigurationProperties annotation. According that docs you can load properties: my.servers[0]=dev.bar.com my.servers[1]=foo.bar.com into bean like this: @ConfigurationProperties(prefix="my") public class Config { private List<String> servers = new ArrayList<String>(); public List<String> getServers() { return this.servers; } } I used @ConfigurationProperties...

Difference between @CacheEvict and @TriggersRemove annotations

caching,annotations,ehcache,spring-annotations,spring-cache

disclaimer: I am working on the Spring caching abstraction (amongst other things). These are two annotations from two different projects. I don't know much about TriggersRemove but from what I can see, it is ehcache specific. The caching abstraction in the Spring Framework is completely decoupled from the underlying infrastructure...

How to capture data parameter from Ajax call in Restful webservice?

jquery,ajax,web-services,rest,spring-annotations

There are two ways you can fix the issue @QueryParam will look for the parameters available in the request URL. So, if you need to use @QueryParam on server-side, you will need to modify the URL and send the data as follows: var b2bValues = "Some String"; var lookupUrl =...

Is it possible to nest controllers/have controllers as inner classes in Spring 4 MVC?

java,spring,spring-mvc,spring-annotations

Tying your class hierarchy to your resource hierarchy should not be the main design driver here. IN Spring MVC, Controllers are simple POJOs to make them easy to test, composition is favored over inheritance, annotations are used to convey meaning and make your code more readable. Nesting Controllers under Controllers...

Inject parameters to constructor through annotation in Spring

spring-boot,spring-annotations

Apple must be a spring-managed bean: @Component public class Apple{ } Fruit as well: @Component public class Fruit { @Autowired public Fruit( @Value("iron Fruit") String FruitType, Apple apple ) { this.apiIdentifier = apiIdentifier; this.apiConfiguration =apiConfiguration; } } Note the usage of @Autowired and @Value annotations. Cook should have @Component too....

Custom Spring annotation for request parameters

java,spring,spring-mvc,spring-annotations

As the guys said in the comments, you can easily write your annotation driven custom resolver. Four easy steps, Create an annotation e.g. @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface UpperCase { String value(); } Write a resolver e.g. public class UpperCaseResolver implements HandlerMethodArgumentResolver { public boolean supportsParameter(MethodParameter parameter) { return parameter.getParameterAnnotation(UpperCase.class)...

Spring - Path variable truncate after dot - annotation

java,spring,rest,spring-mvc,spring-annotations

I've found the solution to this using the ContentNegotiationConfigurer bean from this article: http://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc I added the following configuration to my WebConfig class: @EnableWebMvc @Configuration @ComponentScan(basePackageClasses = { RestAPIConfig.class }) public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(false);...

BeanCreationException from Spring with annotation “@Context” and “@Loggable”

java,spring,service,cxf,spring-annotations

I have now received help on how to resolve this issue. In short, the @Context annotation had to be moved into the method of the interface that the class implemented. The solution is as follows: Removed the private member HttpServletRequest request and its @Context annotation. Add the HttpServletRequest as parameter...

Android as a Client, Server using Spring annotation,communication in JSON format,error while receiving in server

android,spring-annotations,jsonobject

You should create on server side a class that looks like this public class UserDetails { private String id; private String password; private String username; public String getId() { return id; } public void setId(String id) { this.id = id; } ... // other two getter setter } And then...

@PreAuthorize and intercept-url priority

spring-security,spring-annotations

<intercept-url> in XML takes precedence over annotations. <intercept-url> works at URL level and annotations at method level. If you are going to use spring security and spring <form-login /> then the approach below would serve you better. <intercept-url pattern="/public/**" access="permitAll" /> <intercept-url pattern="/restricted/**" access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN', 'ROLE_SOME') @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_SOME')") @RequestMapping("/restricted/aMethod") public...

When should we use @PreAuthorize and @Secured

java,spring,spring-security,annotations,spring-annotations

@PreAuthorize allows you to get a more fine-grained control on the rules to secure o method. You can use SpEL expression inside of it. Securing a method with @Secured gives you the same result as @PreAuthorize but the @Secured is limited and you don't get as much options to tweak...

set resource in spring configuration file

spring,configuration,resources,classpath,spring-annotations

You need to use a ResourcePatternResolver to translate classpath*:dozer/**/*.dzr.xml into a Resource[]. There are 2 main options you can use. Inject the ApplicationContext into your configuration class, cast it to a ResourcePatternResolver and use the getResources method. Al Spring default application context implementations implement the ResourcePatternResolver interface. Create a PathMatchingResourcePatternResolver...

Spring - Autowiring a map

spring,spring-mvc,spring-annotations

Sorry - found the answer nearly straight away - posting answer for completeness Instead of autowiring like this @Autowired private ImageServicesParent imageServicesMap; Use @resource instead and it will work @Resource private ImageServicesParent imageServicesMap; ...

Spring Validation with applyIf attribute in Annotations

java,spring,validation,spring-annotations

As in comment under the question, the syntax should be "name NOT EQUALS 'myValue'" http://www.springbyexample.org/maven/site/sbe-validation/0.92/apidocs/org/springmodules/validation/valang/ValangValidator.html...

PreAuthorize error handling

spring,spring-security,spring-boot,spring-annotations,spring-security-oauth2

Spring Boot docs on error handling: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-error-handling. One way you can control the JSON is by adding a @Bean of type ErrorAttributes. @Bean ErrorAttributes errorAttributes() { return new MyErrorAttributes(); } ...

Spring 3.1.3 + Hibernate Configuration with annotations and with (Dynamic) AbstractRoutingDataSource

hibernate,spring-mvc,spring-security,spring-3,spring-annotations

I found that the problem was in my Dao Layer. In server startup It is not possible to access the current session, so I've done something like: try { Session session = securitySessionFactory.getCurrentSession(); Criteria crit = session.createCriteria(clazz); return (List<T>) crit.list(); } catch (Exception e) { Session session = securitySessionFactory.openSession(); Transaction...

How to prevent Spring from using a @Configuration that's in a test?

java,spring,spring-annotations

How about this: <context:component-scan base-package="my.path" > <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration" /> </context:component-scan> ...

@Autowired finding ambiguous dependencies and still works. How?

java,spring,annotations,spring-annotations

It takes the Category object with the id category because it matches the name of the field. The old spring documentation explain this as: "For a fallback match, the bean name is considered as a default qualifier value." The current documentation explains this a bit clearer. You have a "byName"...

Spring security using @security annotation in controller

java,xml,spring,maven,spring-annotations

The way your web.xml is structured, the file dispatcher-servlet.xml will be loaded twice - once due to the <servlet>...</servlet> tag and then again due to <context-param>...</context-param>. You should remove the reference to dispatcher-servlet.xml from the <context-param>...</context-param> section. The reason why your Spring Security annotations are not working is that you...

Using Spring Security Annotations isFullyAuthenticated v/s hasRole

java,spring,spring-mvc,spring-security,spring-annotations

Does it mean that hasRole implicitly checks for authentication? Not absolutely. It could be hasRole("ROLE_ANONYMOUS") which implies non authenticated users. Note also that isFullyAuthenticted() is not the same as isAuthenticated() since the former required explicit authentication while the latter is more lax accepting remember-me authentiated users. In most cases...

Spring DI based on annotations

java,spring,servlets,dependency-injection,spring-annotations

Well, i find the solution, put the code below in your Servlet public void init(ServletConfig config) throws ServletException { super.init(config); SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); } ...

What happens in Spring if I use the @ActiveProfiles annotation on a configuration class instead use it on the class that defines my beans?

java,spring,annotations,spring-annotations,spring-profiles

If you look at the JavaDoc of ActiveProfiles annotation, it contains this text: ActiveProfiles is a class-level annotation that is used to declare which active bean definition profiles should be used when loading an ApplicationContext for test classes. Meaning it is only supposed to be used to declare active Spring...

Use ?. operator in principal id checks for security

java,spring,security,spring-security,spring-annotations

Yes, this would validate that there is a principal object available. As per the documentation - Authentication is a Principal. public interface Authentication extends Principal, Serializable {} ...

REPEATABLE_READ on Oracle using JPA in Spring

java,jpa,oracle11g,spring-annotations

ORA-17030 error message is JDBC error message produced by Oracle JDBC driver. According to Oracle 11g documentation the following database transaction isolation levels are supported: Read-Commited (default) Serializable Read-Only therefore it's not possible to force Repeatable-Read (ANSI/ISO) isolation level with Oracle database....

Nested autowiring in JUnit test not working

java,spring,junit,jdbctemplate,spring-annotations

The class RegisterVolunteerServiceImpl must be annotated as service. If the class is not annotated as a service it will not befound by the component-scan. So the bean with the name is not instanciated and can not be autowired. In your main application-context you add the bean without component-scan <bean id="registerVolunteerService"...

How to autowire Service with-in JUnit Tests

java,spring,junit,autowired,spring-annotations

Are you trying to use the test itself as a part of the Spring configuration? That's not going to work. What you need to do is: - remove the @Configuration and @ComponentScan annotations from the test itself - create a simple TestConfiguration class: @Configuration @ComponentScan(basePackages={"com.amsb.bariz.base.service"}) @ImportResource("classpath:spring/spring-main.xml") public class TestConfiguration{ }...

Cache is empty after setting up and using ehcache in Spring

java,spring,annotations,ehcache,spring-annotations

I'm not sure about the error message, but you have the @Cacheable on a private method. Since you're making the call from within the same class, it isn't intercepted by Spring and therefore the caching isn't happening. The way that Spring typically works is by creating proxies for each @Service...

Is the @Query annotation in spring SQL Injection safe?

java,spring,sql-injection,spring-annotations

It looks like Spring Data's @Query is just a wrapper around JPA See this SO answer: Are SQL injection attacks possible in JPA?...

Spring custom validation annotation + Validator implementation

spring,bean-validation,spring-annotations

With Spring MVC, just add the custom validator to your controller's data binder: @Autowired private QueryCriteriaValidator validator; @InitBinder public void initializeBinder(WebDataBinder binder) { binder.addValidators(validator); } Otherwise, you'll want to inject the custom validator and call it yourself. @Autowired private QueryCriteriaValidator validator; public void process(QueryCriteria criteria) { check(validator.validate(criteria)); // Continue processing....

Timing Issue with Spring Boot Annotation Configuration

java,spring-boot,spring-annotations

I don't think it is timing issue. You are "in conflict" with this spring feature (from http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/) Even typed Maps can be autowired as long as the expected key type is String. The Map values will contain all beans of the expected type, and the keys will contain the corresponding...

which annotations comes under ?

spring-mvc,hibernate-annotations,spring-annotations

For your scenario, the answer is NO. It's sample. Since you do not add any Spring annotation on Class, it means the bean is not managed by Spring. So the Spring can not do anything on it. It's the same to the hibernate annotation. And for Context:component-scan, I recommend you...

what is the order of bean loading if I have multiple configuration files in spring?

spring,spring-mvc,dependency-injection,spring-annotations

Please have a look at spring documentation You can use Dependency injection @Autowired to refer to beans declared on other java configuration classes but still it can be ambiguous to determine where exactly the autowired bean definitions are declared and the solution for that is to use @Import @Configuration @Import({FooConfig.class,...

How can I disable or override @Autowired bean property with XML configuration

java,spring,spring-annotations,xml-configuration

If you are able to modify your lib which contains EntityLoader, following these 2 step will do the trip : In EntityLoader make your @Autowired optional: @Autowired(required=false) In XML configuration, exclude mysqlSessionFactory and oracleSessionFactory beans from autowire candidates, add autowire-candidate="false" to each sessionFactory: <bean id="mysqlSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" autowire-candidate="false"> <!-- ... config...

Why does not “@Transactional(propagation = propagation.NEVER)” work?

java,spring,transactions,spring-aop,spring-annotations

@Transactional annotations only apply to the Spring proxy objects. For example, if you call allProcessOnDB_second() from some spring bean which injects your service like this @Autowired private MyService myService; ... myService.allProcessOnDB_second(); then myService is Spring proxy, and its @Transactional(propagation = Propagation.REQUIRED) is applied. If you were to call myService.getDeps(id) then...

Grails 2.4.4 spring security role doesn't apply to user

java,spring,grails,spring-security,spring-annotations

The spring Security has an default UserDetailsService, which assigned the Roles to an User. You could debug it to see what going wrong. Or You create your own: https://grails-plugins.github.io/grails-spring-security-core/guide/userDetailsService.html HTH...

Aspectj Spring pointcut on interface doesn't work

spring,aop,aspectj,spring-annotations

Annotations on methods are not inherited by subclasses or implementing classes in Java. This might explain why it does not work. Your expectation might have been that your implementing method inherits the annotation from its interface, but this is not true.

Spring prototype bean reference in Spring @Configuration

java,xml,spring,spring-annotations

You need to remove the entry of Foo from xml. You can define it this way. @Configuration @AnnotationDrivenConfig @ImportXml("classpath:applicationContext.xml") public class Config { @Bean(name = "fooRepository") @Scope("prototype") public FooRepository fooRepository() { return new JdbcFooRepository(foo()); } @Bean(name = "foo") @Scope("prototype") public Foo foo() { return new foo(); } } Approach 2:...

how to convert xml notation to annotation based notation : Spring - Java

java,spring,spring-annotations

You can configure the same beans using JavaConfig as follows: @Component @Configuration public class AppConfig { @Value("${accessTokenEndpointUrl}") String accessTokenUri; @Value("${clientId}") String clientId; @Value("${clientSecret}") String clientSecret; @Value("${policyAdminUserName}") String username; @Value("${policyAdminUserPassword}") String password; @Bean public OAuth2RestTemplate myPolicyAdmin(ResourceOwnerPasswordResourceDetails details) { return new OAuth2RestTemplate(details); } @Bean public...

What is xml-configuration representation of @component in spring

java,spring,spring-annotations,xml-configuration

EDIT From your comment I can see that you want to add listener to AuthenticationEvent public class AuthenticationEventListener implements ApplicationListener<AbstractAuthenticationEvent> { @Override public void onApplicationEvent(AbstractAuthenticationEvent event) { // process the event } } Now you have to put a bean of this type in the same spring context where...

Spring @Scheduled annotation random delay

spring,spring-annotations,spring-scheduled

You can configure the initialDelay through Spring Expression Language: @Scheduled(fixedRate = 600000, initialDelayString = #{ T(java.lang.Math).random() * 10 } ) I don't have an IDE to test that code right now, so you may need to adapt that a bit....