Menu
  • HOME
  • TAGS

Creation of Spring beans without referring or coding in app context file

Tag: spring

I want to know if there is a way to define spring beans which are created without coding them directly in the spring application context file.

Best How To :

You can use component scan.

<context:component-scan base-package="org.example"/>

or @ComponentScan({"com.foo.bar", "org.example"}) for java config

That way spring will scan the secified package for classes annotated with @Component(or its inheritors @Service, @Repository and @Controller) and will register them as spring beans.

You can read more here: http://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s12.html

Spring Data Rest: Return Resources of User

java,spring,spring-security,spring-data-rest

If you are using Spring security integration you can use ACL (maybe to heavy) or simple postFilter like following: public interface ShoppingItemRepository extends CrudRepository<ShoppingItem, Long> { @PostFilter("filterObject.user.getId() == principal.id") @Override Iterable<ShoppingItem> findAll(); } ...

How do I combine Facet and FilterQueries using Spring data Solr?

spring,solr,filtering,facet

I assume you're using Spring Data Solr, from your reference to SimpleFacetQuery. Based on your sample query, the code would look something like this: // creates query with facet SimpleFacetQuery query = new SimpleFacetQuery( new Criteria("lastName").startsWith("Harris")) .setFacetOptions(new FacetOptions() .addFacetOnField("state")); // filter parameters on query query.addFilterQuery(new SimpleFilterQuery( Criteria.where("filterQueryField").is("red"))); // using query...

@RestController throws HTTP Status 406

java,spring,rest,maven

The issue is with the dependencies that you have in pom.xml file. In Spring 4.1.* version the pom.xml dependency for Jackson libraries should include these: <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.4.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.4.1.1</version> </dependency> You...

viewResolver with more folders inside of WEB-INF/jsp is not working in spring

java,spring,jsp,spring-mvc

Say you have a jsp test.jsp under /WEB-INF/jsp/reports From your controller return @RequestMapping("/helloWorld") public String helloWorld(Model model) { model.addAttribute("message", "Hello World!"); return "reports/test"; } ...

Error while setting targetConnectionFactory in UserCredentialsConnectionFactoryAdapter Spring 4

java,spring,jms,spring-boot,spring-jms

The big difference between your code and the example is in the XML config example that myTargetConnectionFactory is actually a bean managed by Spring. You aren't doing that. You are just creating a new object Spring doesn't know about. The magic happens when setting the targetConnectionFactory of myConnectionFactory. Even though...

Transaction error in Spring

java,spring,jpa

In the stacktrace, there are no Spring AOP class listed between these two lines: at com.vizaco.onlinecontrol.service.impl.UserServiceImpl.saveUser(UserServiceImpl.java:51) at com.vizaco.onlinecontrol.controller.UserController.createUser(UserController.java:112) Your Dependency Injection is not setup right.. the Controller should be getting a Spring Bean of UserService ...

Spring Boot - How to set the default schema for PostgreSQL?

java,spring,hibernate,postgresql

You can try setting the default schema for the jdbc user. 1) ALTER USER user_name SET search_path to 'schema' 2) Did you try this property? spring.datasource.schema http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html...

JdbcTemplate Mockito ClassCastException

spring,mockito,classcastexception

Remove the answer = Answers.RETURNS_SMART_NULLS. Test passes when I remove that. What does that feature do? The default null behavior works fine for me. As a bonus, you can also use the MockitoJunitRunner to clean up the code a bit... @RunWith(MockitoJUnitRunner.class) public class DaoJdbcTest { @Mock private JdbcTemplate jdbcTemplate; @InjectMocks...

Hibernate : Stale state exception

java,spring,hibernate,spring-mvc,transactions

The reason for the exception is that you were loading a GroupCanvas before and this has a reference to the GroupSection. Then you delete the GroupSection but when the transaction commits GroupCanvas still holds a reference to the deleted GroupSection and you get the StaleStateException. As you saw, deleting the...

How to apply HandlerInterceptor to Spring Boot Actuator endpoints?

java,spring,spring-mvc,spring-boot

You can use an EndpointHandlerMappingCustomizer to configure the interceptors of the Actuator's endpoints. For example: @Bean public EndpointHandlerMappingCustomizer mappingCustomizer() { return new EndpointHandlerMappingCustomizer() { @Override public void customize(EndpointHandlerMapping mapping) { mapping.setInterceptors(new Object[] { application.executeTimeInterceptor() }); } }; } ...

Bean Creation exception, Injection of autowired dependency failed

java,spring,hibernate,spring-mvc

As you can see in the stacktrace: nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool The class GenericObjectPool is missing in your classpath. So you have to add the commons-pool.jar to your project which contains this class....

How to catch socket exceptions on TcpInboundGateway?

java,spring,sockets,spring-integration

We should probably change that to propagate the exception, but it would be a behavior change so we'd probably have to do it in 4.2 only, unless we make it an option. Actually, after further review; this can't be accommodated - you have to handle the exception via the connection...

Spring Boot extending CrudRepository

java,spring,hibernate,spring-boot,spring-data-jpa

There are lots of ways you could probably accomplish this. If you really need absolute control try this interface FoobarRepositoryCustom{ List<Foobar> findFoobarsByDate(Date date); } interface FoobarRepository extends CrudRepository<Foobar, Long>, FoobarRepositoryCustom public FoobarRespoitoryImpl implements FoobarRepositoryCustom{ @PersistenceContext private EntityManager em; public List<Foobar> findFoobarsByDate(Date date) { String sql = "select fb from Foobar...

Spring: Response time

java,spring,spring-ws

Yes, implementing an EndpointInterceptor is the best fit for this task, as it gives you access to the SOAP messages through the MessageContext. See the Reference Documenation.

How can implement long running process in spring hibernate?

java,spring,hibernate

I recommend you to use DeferredResult of Spring. It´s a Future implementation, that use the http long poling technique. http://docs.spring.io/spring-framework/docs/3.2.0.BUILD-SNAPSHOT/api/org/springframework/web/context/request/async/DeferredResult.html So let´s says that you will make a request, and the server it will return you the deferredResult, and then your request will keep it open until the internal process(Hibernate)...

Override Spring form error messages

java,spring,default,custom-errors

You can override the defaults by creating custom messages in your localization bundle with keys following conventions defined by Spring's DefaultMessageCodeResolver. For the sake of completeness here is the relevant part of its documentation: Will create two message codes for an object error, in the following order (when using the...

Dynamic fields thymeleaf list iteration

spring,spring-mvc,spring-boot,thymeleaf

Actually when binding fields to a form, in order to acces to a list with th:each. As the doc specify, we should use the two variable item, and phoneStat this way and not just phoneStat : <div th:each="item, phoneStat : *{phones}"> <select th:field="*{phones[__${phoneStat.index}__].variety}" > <option> </option> </select> <div class=" input-field...

Spring Data Rest executes query but returns 500 internal Server Error

java,spring,rest,spring-boot,spring-data-rest

Hum... This is strange but I found this question and added a controller to call the method and it worked like a charm... Obv this is not a fix, but it is a good workaround... EDIT: The error happens because it is expecting an entity, so all I had to...

Spring, Java : Passing Generic object List as return type

java,spring,spring-mvc,generics,casting

You should probably use a common interface shared by both classes. Declaring an interface like, for instance: public interface INotes{ } public class GroupNotes implements INotes{...} public class Notes implements INotes{...} Your code would become: @PreAuthorize("hasRole('ROLE_USER')") @RequestMapping(value = "/findnotebydays/{days}/{canvasid}/{mode}") public @ResponseBody List<INotes> findNotesByDays(@PathVariable("days")int days, @PathVariable("canvasid")int canvasid, @PathVariable("mode")boolean mode ){ if(!mode){...

Spring data repository QueryDslPredicateExecutor without pageable count

spring,spring-data,spring-data-jpa,querydsl

This is basically invalid usage of the query derivation mechanism. Executing Predicate instances and query methods are a distinct mechanisms that cannot be intermingled. You basically declare a query method that doesn't take any parameters (does not have any criterias) bit then takes a Predicate that Unfortunately the methods declared...

Logging operations in lightadmin

java,spring,logging,lightadmin

You can use the class AbstractRepositoryEventListener like it's show on the LightAdmin documentation here Add you logger insertion by overiding onAfterSave, onAfterCreate and onAfterDelete into your own RepositoryEventListener. After you just need to register your listener like this public class YourAdministration extends AdministrationConfiguration<YourObject> { public EntityMetadataConfigurationUnit configuration(EntityMetadataConfigurationUnitBuilder configurationBuilder) { return...

Is it possible to construct an object partially with Spring DI and partially with Jersey DI?

spring,dependency-injection,jersey,jersey-2.0,hk2

It should work. Given you have the required Spring-Jersey integration dependency[1] and have correctly configured the application[2] 1. See Spring DI support in Jersey 2. See official Jersey Spring example What happens is HK2 (Jersey's DI framework) will look for an InjectionResolver for the @Autowired annotation, in order to resolve...

Spring Mobile apps to be deployed in emulator

javascript,android,html5,spring,spring-mvc

Since you're not actually developing a mobile app (which would be installed on the mobile device itself) but a web page that detects and supports mobile devices, you don't need an Android emulator. What you do need is a browser that allows emulating a mobile client - Chrome has a...

Trouble with Login using Spring Boot and JDBC Security

spring,spring-security,spring-boot

There are 2 things flawed in your setup. You should post to /login instead of /j_spring_security_check as that is the new URL when using java config (and in Spring 4 for XML config also). You have set the usernameParameter to name and your form still has username. Fix those flaws...

Cron expression must consist of 6 fields (found 1 in “#{systemEnvironment['db_cron']}”)

spring,groovy,cron,spring-el

You should set env variable like you do: export db_cron="0 19 21 * * *" then restart your ide if you are using or restart your terminal session. @Scheduled(cron = "${db_cron}") def void schedule() { ... } I tried it and here is my screenshot. Everything works as expected......

Jersey serializing null values to json : How to skip

java,json,spring,serialization,jersey-2.0

Assuming, you are using Jackson for serialization, you can use the @JsonInclude(Include.NON_NULL) to your class to exclude the null values.

Using Spring Security, what's the right way to manage authorization to query responses?

java,spring,spring-security

You're trying to query a list of items that a user may not be the owner of but should be able to access anyways, yes? Like shared documents or some-such. If that is the case, you need to upgrade to Spring Security 4 . It allows for SpEL expressions with...

shall I use Spring framework for a performance-critical proxy application? [closed]

java,spring,authentication,servlets

Before re-writing your code first thing you should analyze is why do you require Spring framework? What problem are you facing in your current architecture? Just because size of the response data stokes up shouldn't be the only reason to re-write your code. You can better design your existing code...

cleanest way to create multiple beans of the same class with different properties

java,spring,dependency-injection,spring-bean,spring-properties

Spring already supports that out of the box, since Spring 0.9 (but not many people know about that). You would need to modify your property file slightly. student.(class)=your.package.here.Student student.(abstract)=true jim.(parent)=student jim.firstname=Jim jim.lastname=Wright jim.age=21 ... Other student based definitions here. Now you can use a BeanFactory together with a PropertiesBeanDefinitionReader DefaultListableBeanFactory...

Is it possible to have “connection preparation” with Spring / JPA persistency

java,spring,jpa,spring-data

Using AOP would seem to be one approach: an example of using AOP to enrich Spring Data repositories can be found at the below: https://github.com/spring-projects/spring-data-jpa-examples If you can get a reference to the injected EntityManager within the advice then you should be able to get the underlying connection from that...

GenericApplicationContext cannot be cast to WebApplicationContext : Spring Web Flow

java,spring,spring-mvc,classcastexception,spring-webflow-2

FlowBuilderServices is meant to be a Spring-managed bean, but in your config it is just a new instance. It likes to be ApplicationContextAware and InitializingBean, but that is gonna work only if managed by Spring. The solution is simple: put @Bean on getFlowBuilderServices() method. And I think you should also...

Can't deserialize json response from Flurry API

java,json,spring,flurry

you should be able to parse it with GSON, using the @SerializedName annotation, like this : public class FlurryAppMetric { @SerializedName("@metric"); private String metric; @SerializedName("@startDate"); private String startDate; @SerializedName("@endDate"); private String endDate; @SerializedName("@generatedDate"); private String generatedDate; @SerializedName("@versionDate"); private String version; @SerializedName("day"); private ArrayList<FlurryMetric> day; } public class FlurryMetric { @SerializedName("@date");...

how to autowire in spring for test classes?

spring,testing

Here is a skeleton of how your test class should look like @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") @TransactionConfiguration(transactionManager = "<< YOURTRANSACTIONMANAGER >>", defaultRollback = true) @Transactional public class ServiceTest { //The name of your resource/service should be the same as defined in your bean definition @Resource private YourService service; @Test public void testYourService()...

Spring Data JPA user posts

java,spring,jpa,data

Create a second entity (java class) e.g. UserPost: @Entity @Table(...) public class UserPost { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private long userId; ... } Then add @OneToMany relationship field to User. Cascading, lazy-loading, etc. depends on how you'd use it. It'd look like this inside User: @OneToMany(cascade={...}) @JoinColumn(name="userId")...

How to conditionally invoke spring validators

java,spring,validation

There's two ways to do this. You can either create a custom validation annotation and validator which checks the value of method and then applies to appropriate validations to the other fields use validation groups, where you manually check the value of method, then choose which group to use; your...

Can't Override Equals method on Java when calling contains

java,spring,hibernate

You need to provide an complmentary hashCode() method whenever providing an equals() method and visa-versa. The reason for this is to fulfil the API contracts when interacting with the objects in collections. See the site for tips on creating the code hashcode-equals The Java Docs have more information about the...

Cannot create bean when start the application

java,spring,javabeans,sftp,job-scheduling

please visit DefaultSftpSessionFactory it has following : setUser public void setUser(String user) The remote user to use. This is a mandatory property. Parameters: user - The user. See Also: JSch.getSession(String, String, int) ...

spring.xml not packaged in executable jar

java,spring,maven,executable-jar

If you're using maven, you can put your XML files in src/main/resources. By default, all files placed in the resources folder will be included in the jar file and will be accessible by your application.

Spring: @NestedConfigurationProperty List in @ConfigurationProperties

spring,properties,configuration,spring-boot

You need to add setters and getters to ServerConfiguration You don't need to annotate class with nested properties with @ConfigurationProperties There is a mismatch in names between ServerConfiguration.description and property my.servers[X].server.name=test ...

How to set property using “tasklet ref” tag

spring,spring-batch

Isn't this what you want: <step id="validaSituacaoStep"> <tasklet ref="validarSituacaoTasklet "/> </step> <bean id="validarSituacaoTasklet" class="my.package.tasklet.ValidarSituacaoTasklet" scope="step"> <property name="situacao" value="EM_FECHAMENTO"/> </bean> UPDATE Based on the comment left, this should work: <step id="validaSituacaoStep"> <tasklet> <bean class="my.package.tasklet.ValidarSituacaoTasklet" scope="step"> <property name="situacao" value="EM_FECHAMENTO"/>...

Spring Core-Setter Injection

spring

whenever you have something like this in your property file <bean id="A" class="com.common.A"> <property name="b" ref="B" /> </bean> spring container by default searches for setter of that property i.e setPropertyName() after invoking a no-argument constructor of that class whose bean is being prepared, and as it confines to JavaSpecification it...

Default Spring bean when profile is not present

java,spring,spring-mvc,spring-profiles

The problem here is that your class DevController inherits from DefaultController. Keep classes separate. Don't extend DevController with DefaultController even if the contents are same.

Why is my Spring Boot autowired JPA Repository failing JUnit test?

java,spring,junit,spring-boot

Exception comes from this line: ReflectionTestUtils.setField(userResource, "userRepository", userRepository); Second parameter of setField method is a field name. UserResource has field "repository" - not "userRepository" as you try to set in your test....

Is it possible to permit all users except anonymous one?

java,spring,spring-security

You can use the isAuthenticated either in xml format or annotation format: xml spring configuration: <intercept-url pattern="/pattern/page.html" access="isAuthenticated()" /> Annotation: @PreAuthorize("isAuthenticated()") ...

Use $or operator in @Query annotation in spring data mongodb repository

java,spring,mongodb,spring-data-mongodb

Per MongoDB reference for $or, your Query should be @Query("{'$or':[ {'type':?0}, {'name':?1} ]}") you'll need to give pass type and name params....

Importing Spring MVC Project Manually to Eclipse

java,eclipse,spring,spring-mvc

you will extract zip file and go to inside folder in templete.zip is import succesully into eclipse IDE.i have tested.

Spring Resttemplate login fails

java,spring,spring-mvc,spring-security,csrf

You seem to have upgraded Spring Security to 4.x as well (evidenced by xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd). Unfortunately, Spring Security 4.x is not a drop-in replacement for 3.x. You will need to review the Official Migration Guide for configuration elements that need to be tweaked. However, some of the ones that stand...

Spring OAuth2 not giving refresh token

java,spring,spring-security,spring-security-oauth2

The client needs authorizedGrantType "refresh_token". Try this @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("resource-serv") .scopes("read") .resourceIds("my-resource") .secret("secret123") .and() .withClient("app") .authorizedGrantTypes("client_credentials", "password", "refresh_token") .scopes("read") .resourceIds("my-resource") .secret("appclientsecret"); } ...

How to implement customer subdomain in Spring framework

spring,saas,multi-tenancy

Create a custom filter which parses whole url and extracts subdomain, then check if the user is on proper domain with proper rights. Also worth mentioning Nginx should redirect "*.yourdomain.com" so all subdomains don't have to exist in Nginx, they could exist in database and each user has his unique...

Not Able to Resolve View Using Spring boot

spring,spring-mvc,spring-boot

Here could be two issues one them are dependencies. 1.These three dependencies could help you: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId>...