w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
When does spring use AOP without Aspectj.jar?
It doesn't use AspectJ by default, but uses proxies (either JDK interface proxies or CGLIB proxies). So, when you inject a transactional bean into another bean, what you get injected is in fact a proxy to your actual bean instance, which intercepts the method calls and starts/commits/rollbacks transactions. More in the documentation, of course.

Categories : Spring

log the exception in spring using aspectJ?
Its possible to simply remove the try/catch from your code and simply log the exception in your aspect. public void someMehtod(){ int i=2/0; System.out.println("i value : "+i); } Because you don't re-throw the exception in the aspect then it won't bubble up. Although this is possible I strongly advise you to think more about what you are trying to do here. Why do you need to log the fact that an exception has been thrown? Exceptions aren't necessarily only for errors but can occur in normal code journeys. Simply logging only the exception name is unlikely to help you debug the problem. Therefore, you will probably want a bespoke log message for each catch block. If you do find repetition you could create a method to log out the result. Hope this helps, Mark

Categories : Java

How to use AspectJ load time weaving with Tomcat? (without Spring)
Well, probably my answer is too late, but I hope it will help others. Some time ago I faced the same problem. Two years were passed, so I use Tomcat 7 and AspectJ 1.8.8 now. So, first of all you don't need to change system class loader. There is java agent feature since Java 5, so AspectJ now uses it for load time weaving. For Tomcat just add this to your %CATALINA_HOME%setenv.bat: set JAVA_OPTS=-javaagent:c:path oaspectjweaver.jar set CLASSPATH=%CLASSPATH%;c:path oyouraspect Enjoy! :)

Categories : Tomcat

Spring @AspectJ @Pointcut to match regardless of argument list
Testing the resulting WAR shows that the aspect is, in fact working, and that all the methods of my service class that I want to be point cuts are point cuts. I conclude that this is actually a flaw in the Eclipse Spring plug-in: it does not show all the join points when a @Pointcut matches multiple locations, but instead shows only one, which it chooses somewhat arbitrarily.

Categories : Eclipse

AspectJ aspect not weaving Spring MVC methods with @RequestMapping annotation
The pointcut only matches methods without any arguments. The displayHomePage method takes a map parameter. Try pointcut publicOperation() : execution(public * com.mycompany.myproject..*(..)); With the added .. this pointcut will match any public methods within your specified package, regardless of how many arguments there are - if any.

Categories : Spring

Load-time weaving with AspectJ in the Spring Framework Private methods
Your first question: Private methods are not included when the log is weaved around the method. Is there a setting in the xml settings for spring to allow private methods to be weaved or is there another way around this? If you want to weave private methods, use full AspectJ and therein a privileged aspect, not Spring AOP. The Spring manual says: If your interception needs include protected/private methods or even constructors, consider the use of Spring-driven native AspectJ weaving instead of Spring's proxy-based AOP framework. This constitutes a different mode of AOP usage with different characteristics, so be sure to make yourself familiar with weaving first before making a decision. Your second question: I have to include all packages that a

Categories : Spring

Jersery ExceptionMapper does not intercept Exceptions thrown from Spring AspectJ annotated Aspects?
Ok I found the solution: Problem was that my ExceptionMapper was typed to map XBBridgeExceptions ( ExceptionMapper ). But Spring AOP aspect (RequestValidationAspect) throws UndeclaredThrowableException (which is a wrapper round XBBridgeException). Since UndeclaredThrowableException is a RuntimeExpcetion it was not intercepted by my mapper.Solution was to write another ExceptionMapper for UndeclaredThrowableException exceptions.

Categories : Spring

Log the return value of a method using spring aop
Using @AfterReturning with a returnValue param. You could then interogate the object returned This is an example where I do it on everything but get methods in a repository @AfterReturning(value = "@target(org.springframework.stereotype.Repository) && !execution(* get*(..))", returning = "returnValue") public void loggingRepositoryMethods(JoinPoint joinPoint, Object returnValue) { String classMethod = this.getClassMethod(joinPoint); if(returnValue !=null) { //test type of object get properties (could use reflection) log it out } else { //do logging here probably passing in (joinPoint, classMethod); } }

Categories : Misc

Spring MVC - Return static page
Please remove the annotation @ResponseBody. Your browser should be redirected to the desired page once the annotation is removed. This annotation indicates that the value returned by a method in your controller should be bound to the web response body. In your case, you do not need that: you need Spring to render page /resources/Post.html, so no need for this annotation.

Categories : Java

set @RequestMapping value to return spring controller
If you want to return the string that comes after the slash, you could do something like this: @RequestMapping(value = "/{foo}", method = RequestMethod.GET) public @ResponseBody String homeForm(@PathVariable("foo") String foo) { return foo; }

Categories : Spring

difference between Spring mvc redirect and general jsp name return
With the first one user will receive HTTP 302 response to redirect into DummyRedirectPage.htm. If the handler was mapped to a POST method, this will force user to perform GET to DummryRedierctPage.htm On the second one your view resolver will resolve "somejsp" into an actual view. No HTTP 302 response is given to user. Please read about PRG (Post Redirect Get) design pattern to find out why this matters.

Categories : Spring

How to return a XML response from a POST rquest with Spring MVC?
There are many ways to achieve this. One is to use MarshallingView and XStreamMarshaller Firstly add following jars to your classpath (maven dependencies): <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.4</version> </dependency> Then configure a Marshaller on your spring xml configuration <bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"/> Assuming you have following bean you want to Marshal (ie: display as XML) public class MyMe

Categories : Java

Return Excel downloadable file from Spring
You need to set the Content-Disposition header. response.setHeader("Content-disposition","attachment; filename=" + yourFileName); and write your bytes directly to the response OutputStream. File xls = new File("exported.xls"); // or whatever your file is FileInputStream in = new FileInputStream(xls); OutputStream out = response.getOutputStream(); byte[] buffer= new byte[8192]; // use bigger if you want int length = 0; while ((length = in.read(buffer)) > 0){ out.write(buffer, 0, length); } in.close(); out.close(); The above is relatively old. You can construct a ResponseEntity with FileSystemResource now. A ResourceHttpMessageConverter will then copy the bytes, as I have suggested above, for you. Spring MVC makes it simpler for you rather than having you interact with inte

Categories : Java

Which return type use in spring mvc in @RequestMapping method?
Unless your return type is void or you annotate your method with @ResponseBody, Spring MVC will try to resolve a View to render the response. Therefore, you must somehow point the framework to a View instance or to the name of a view as String in your returned value (or rely on the implicit resolving and perhaps only return the Model); if you return a name (either as a mere String or embedded in a ModelAndView), that will then be passed to a configured ViewResolver to obtain an actual View instance. The ModelAndView container does hold a reference to a View or view name and also embeds the model to use.

Categories : Java

Configure Map in Spring to return prototype bean
I think that since ItemFactory is singleton it all it's life holds reference to same instance of Bean no matter that referenced bean is prototype scoped. Spring doesn't care about prototype scoped bean destruction, it simply creates new instance of bean when it's referenced from singleton and that's it. You are referencing bean with smaller scope (prototype) from bean with larger scope (singleton), that's problematic. See referencing prototype beans from singletons There are two solution for this case: Use method injection as described in link above. In getItem() method retrieve beans directly from Spring application context.

Categories : Java

AspectJ performance
There is no general way to answer the question. It really depends on how broad or narrow the scope of your pointcuts is and how expensive the code executed in your advice is. Usually the overhead is small unless you use a very unfortunate combination of dynamically determined pointcuts and expensive/slow advice code to be woven into the target joinpoints. Imagine you add a certain code snippet to many methods. The overhead depends on the snippet, the number of places you add the snippet to and the number of calls for all those methods where you added the code. This is what an aspect weaver does: weave compiled bytecode into your classes. The only difference is that it is done automatically, you do not have to scatter the snippets throughout your code base manually.

Categories : Performance

AspectJ "around" and "proceed" with "before / after"
With this Test @Aspect public class TestAspect { private static boolean runAround = true; public static void main(String[] args) { new TestAspect().hello(); runAround = false; new TestAspect().hello(); } public void hello() { System.err.println("in hello"); } @After("execution(void aspects.TestAspect.hello())") public void afterGetPanel(JoinPoint joinPoint) { System.err.println("after " + joinPoint); } @Around("execution(void aspects.TestAspect.hello())") public void aroundGetPanel(ProceedingJoinPoint joinPoint) throws Throwable { System.err.println("in around before " + joinPoint); if (runAround) { joinPoint.proceed(); } System.err.println("in around after " + j

Categories : Java

JaCoCo and Aspectj
I had the same problem when using java 1.6. aspectj compile-time weaving produced class files which jacoco found to be invalid. The combination of Java 1.7 + aspectj 1.7.3 + jacoco 0.6.3.201306030806 works for me.

Categories : Java

Spring Social Twitter Search does not return any tweets
It doesn't look like you're doing anything wrong. But it kind of depends on what the query is. I'd bet if you search for "fdshfjads" you won't find much. But if you search for "#VineApp", there'd probably be more than a few tweets. Out of curiosity, which version of Spring Social Twitter are you using?

Categories : Spring

Spring MVC 3 ModelAndView: controller method to return several views
Multiple views are perfectly possible. Considering the HTML: <select id="attr1" name="attr1"> <option value="1">A</option> <option value="2">B</option> </select> Then the controller method should be: @RequestMapping(value = "/aaa", method = RequestMethod.POST) public ModelAndView methodName(@RequestParam(value = "attr1") int attribute) { if (attribute == 1) { return new ModelAndView("view1"); } else if (attribute == 2) { return new ModelAndView("view2"); } else { return null; // Empty 200 OK just to be sure if other attr is received } }

Categories : Spring

Spring 3.2 @Async task with return type of Future
The ExecutorService can schedule Callable and return a Future object. The Future is a placeholder that contains result once it's available. It allows you to check if result is there, cancel the task, or block and wait for the results. The Future is useful only when you are expecting some object/value from the task. Correct way to do the Future call is: Future<Integer> futureEvenNumber = executorService.submit(new NextEvenNumberFinder(10000)); // Do something. try { Integer nextEvenNumber = futureEvenNumber.get(); } catch (ExecutionException e) { System.err.println("NextEvenNumberFinder threw exception: " + e.getCause()); } The NextEvenNumberFinder class: public class NextEvenNumberFinder implements Callable<Integer> { private int number; public NextEvenNumberFinde

Categories : Java

certain parameter should be attached on every return by controller using model in spring MVC
You can use the postHandle method of a Spring HandlerInterceptor. See this blog http://www.mkyong.com/spring-mvc/spring-mvc-handler-interceptors-example/ for an example of how to implement a HandlerInterceptor

Categories : Java

Downloading file from Spring controller and return String
If I understand you correctly, what you want to do is either send the user to a page, like a "It didn't work/validate" page OR send the file. If this is the case, what we did to solve it was to return a ModelAndView from our handler. You can include it as a parameter to your handler as well, and Spring will create one for you and you can just return it. If the form input failed validation, we set the View on the ModelAndView to a custom view that would set the Content-Disposition and related headers, then got the OutputStream from the HttpServletResponse and wrote the file out as bytes. Something like this (pseudo code, so may need tweaking): @RequestMapping("/myHandler") public ModelAndView myHandler(@ModelAttribute("myBean") MyBean myBean, BindingResults results, ModelAndView mav) {

Categories : Java

Spring: Return JSON response From A Java Bean
We use fastjson to JSONize java beans. It's fast and convenient. public @ResponseBody String showLesson() { Map<String, Object> map = new HashMap<String, Object>(); return JSON.toJSONString(map); }

Categories : Java

spring-data-neo4j findByPropertyValue method always return null?
Did you try to implement your own find method in the repository like: Iterable<Social> findByUserId(Long userId); Are the indexes created correctly (see Null return using GraphRepository from Spring Data for Neo4j)?

Categories : Java

Unsure how to return generated column id value using Spring jdbcTemplate and PreparedStatementSetter
Generated keys may be returned with JdbcTemplate#update(PreparedStatementCreator,KeyHolder) method. But to achieve this you need to change your request, based on org.springframework.jdbc.core.PreparedStatementCreatorFactory. Instead I would recommend to use for inserting SimpleJdbcInsert utility class. If your DB fields are the very same as your entities' fields, then you can simply do as following: Number key = jdbcInsert.executeAndReturnKey(new BeanPropertySqlParameterSource(entity)); //set generated key if (key != null){ entity.setId(key.longValue()); } If it is not (as in your case), then //define parameters Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("FIRSTNAME", pupil.getFirstname()); parameters.put("SURNAME", pupil.getSurname(

Categories : Java

Spring/Hibernate - validating groups manually and return a BindingResult
I had a similar issue, and ended up extending the SpringValidatorAdapter class so that I could perform the validation and specify the groups. ExtendedSpringValidatorAdapter adapter = new ExtendedSpringValidatorAdapter(validator); adapter.validate(objectToValidate, bindingResult, Class1.class, Class2.class); Here is the definition of the extended validator: package com.example.validator; import org.springframework.beans.NotReadablePropertyException; import org.springframework.validation.Errors; import org.springframework.validation.FieldError; import org.springframework.validation.beanvalidation.SpringValidatorAdapter; import javax.validation.ConstraintViolation; import javax.validation.Validator; import javax.validation.groups.Default; import java.util.Set; public class ExtendedSpri

Categories : Spring

Returning list using @Responsebody or return ModelAndView from spring controller which one better
Viswam, The answer depends mostly on your application and the functionality you want to achieve, there is no standard solution here. If your application is a single page application (read this wikipedia article) or you want RESTful application, I would suggest to stick with @ResponseBody, reason is simple, it supports AJAX and basically doesnt change the page from Server side. You can easily populate any complex table using plain JavaScript or jQuery from the JSON response you receive. Also if I were to think, I wouldn't want to waste my resources at server side for populating data in JSP and then send it over to client(browser) when it can do this by itself. But this is strictly a personal choice/preference. And, If you need to redirect to or reload a page, I believe ModelAndView is

Categories : Java

Will Spring's @CachePut annotation work with a void return type?
Yes, it's because void return type. The @CachePut annotation places the result of method into the cache. In your case there is no result so nothing is put to the cache. Change method signature to return User: public User addUser(User user) { ... }

Categories : Spring

Postgresql batch update with Spring. How to write a function with no return value
As I understand it your problem is that PostgreSQL will add a row to the result set even though your function didn't return one. A quick test showed that, in fact, these are returning a null from PostgreSQL. What I do (and I realize this may not be the Spring way) is to have a function that does what I need it to do, and returns a useful value. Then I take that value and use it for sanity checking purposes. I might, for example, return the total number of rows updated (or perhaps the most recent version of the parent-most row) and hand that back to the application to use. However, yes, you will need to find another way to do this.

Categories : Spring

SpringAOP introductions with AspectJ
First you need to define the bean Test in your configuration file: <bean id="test" class="Test" /> Then in main, get this bean from ApplicationContext: Test test1 = (Test) context.getBean("test"); Now, from test1 reference, you can only invoke method defined in Test bean. To use the newly introduced behaviour, you need to typecast the reference to the interface containing that behaviour: ITest2 test2 = (ITest2) context.getBean("test"); Then, you can access the method of Test2 from this reference: test2.test2(); This will invoke the method defined in the bean as specified in the defaultImpl attribute of @DeclareParents annotation.

Categories : Java

Get parameters from two functions with AspectJ
I solved the problem with 2 poincuts and 2 advices. I made another poincut to take the parameter from actionPerformed, using execution. This is the second poincut and advice: pointcut change2(ActionEvent e) : execution(* *.actionPerformed(..)) && args(e); before(ActionEvent e) : change2(e) { System.out.print("Changing from " + ((MyButton)e.getSource()).getColor().toString()); }

Categories : Java

AspectJ LTW not working with JMX remote
I finally found a solution: I need to add “-Xbootclasspath/p:libs/aspectjweaver-1.7.3.jar;libs/aspectjrt-1.7.3.jar” to my command line. With this option, everything work fine. The full command line is: java -javaagent:.libsaspectjweaver-1.7.3.jar -Xbootclasspath/p:libs/aspectjweaver-1.7.3.jar;libs/aspectjrt-1.7.3.jar -cp ".libsProtoApp-v0.0.1-SNAPSHOT.jar;.libs*" -Xms64m -Xmx512m -XX:MaxPermSize=128m -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=7777 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Daj.weaving.verbose=true -Dorg.aspectj.weaver.showWeaveInfo=true -Dlogback.configurationFile=file:.logback.xml org.iiter.continuum.protos.simple.App Thanks to Andy Clement fo

Categories : Java

Declare parents aspectj
What you used there is core aspectj, so if you want to use Spring AOP, but not xml config then this is what you should do (not tested): @Aspect public class ASaveResults { @DeclareParents(value="ISaveResults") public static ILearningData interf; public void saveResults() { System.out.println("saver aspect"); } }

Categories : Spring

AspectJ aspects ordering
@DeclarePrecedenceis what you want to use in @AspectJ style, if native syntax is not your coding style of choice.

Categories : Java

How to run my project so that they use my AspectJ aspects
Make sure that you have AspectJ Development Tools plugin installed Convert your project to AspectJ project using context menu Configure/Convert to AspectJ project Your project should work now using internal aspects. If the aspects are external - put them on your class path.

Categories : Java

Exposing context with AspectJ
There is no way to access local variables from a method that is being advised by an aspect. This is because local variables are not exposed via any joinpoints. If you need to access local variables, then you will have to refactor the target code so that they are exposed. You can do something like this: public class Sample { public static void sendMessage(String message) { String x = getX(); System.out.println(message); } public static String getX() { return "string x"; } public static void main(String[] args) { sendMessage("my message"); } } Then, you can advise the call of the method getX. If you need to access both message and x, this is still possible, but you would need to use a wormhole pattern to do so. I can explain if

Categories : Java

Junit Mockito with spring - test case for the Json String return
hmmm. You could try mockMvc.perform(get("/user-byName").sessionAttr("userClientObject", userClientObject)) .andExpect(status().isOk()); to setup userClientObject in test fixture. What does "return getUserByName(userClient, firstName, lastName);" exactly do? If it doesn't involve external dependence, just assert your return in andExpect(jsonPath()) clause. I thought it should be @SessionAttribute by the way.

Categories : Spring

what should be return type of a query which fetches 2 columns in spring data neo4j?
In that case queries return an Iterable<Map<String,Object>> which allows you to iterate over the returned rows. Each element is a map which you can access by the name of the returned field and using the neo4jOperations conversion method to cast the value object to its proper class, i.e.: Iterable<Map<String, Object>> it = getNodes(...); while (it.hasNext()) { Map<String, Object> map = it.next(); obj = neo4jOperations.convert(map.get("member"), Node.class); ... }

Categories : Java

Fill Spring model attribute with value return from completion of Thread Excecution
If I understand correctly, you do not want the model to contain the Thread object, you want it to contain the result computed by the thread. You need to look at the Future class. But even then, I doubt it will help you much; the JSP rendering code will want the result of the thread very soon after your controller method returns, so there will not be much time for the value to be computed. You need to reconsider why you are using threads at all.

Categories : Java



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