w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
When to declare a spring bean as private static when the bean is singleton?
If by declaring the bean as static, you mean something like @Bean public static MyBean myBean() { return new MyBean(); } then the benefit of this is to have your bean generated before the instance method beans. You would use this for example with a BeanFactoryPostProcessor which states: Application contexts can auto-detect BeanFactoryPostProcessor beans in their bean definitions and apply them before any other beans get created. The Spring Java configuration way for these to be auto-detected and initialized before the rest of your beans is to declare and initialize them with static methods. For example, @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } Spring will de

Categories : Spring

How can I access Spring bean from Message-driven bean in JBoss AS 7
A static holder for the context is not really a good idea. To make your beans available to other applications in a Java EE environment, you should consider making use of JNDI. Unfortunately, there is no plain JNDI exporter available out of the box, but it's fairly easy to write one yourself, as shown in this blog post: http://maestro-lab.blogspot.ro/2009/01/how-to-export-spring-managed-bean-to.html There is however a JndiRmiServiceExporter that you may want to look at. Once your beans are bound to names in JNDI, they can be referenced using standard CDI in your message bean without worrying about class loading issues.

Categories : Spring

spring bean properties with singleton
It depends on what you say to Spring to do. Spring has an Inversion Of Control container that manages the instances of the objects. Depending on the scope you give to your objects, it will make them singletons or not. More info: http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch04s04.html

Categories : Java

How do I initialize a singleton spring bean when it is needed rather than on start up?
set them to lazily initialize by adding lazy-init="true" For example: <bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/> in bean definition xml And in annotation based configuration @Lazy(true)

Categories : Java

How to create a spring bean from an enum singleton's factory method
This ought to work: <util:constant id="exchangeFactory" static-field="com.xeiam.xchange.ExchangeFactory.INSTANCE" /> <bean id="mtGoxExchange" factory-bean="exchangeFactory" factory-method="createExchange"> <constructor-arg value="com.xeiam.xchange.mtgox.v2.MtGoxExchange" /> </bean> Give it a shot.

Categories : Java

Error creating bean with name 'flowBuilderServices': Initialization of bean failed with spring web flow
You need a reference to a view resolver. like so: <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean>

Categories : Maven

Spring Testing - Inject mocked bean with nested bean dependencies
You could use standalone mockMvc if you do want to unit test the controller. private MockMvc mockMvc; private SomeController controller = new SomeController(); @Mock private ResourceAdminService resourceAdminService; @Before public void setup() throws Exception { controller.setResourceAdminService(resourceAdminService); this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); } If you still want to setup an ApplicationContext, but it's too annoying with the DI. Maybe you'll interested in this article(http://java.dzone.com/articles/how-use-mockstub-spring). But the Strategy C:Dynamic Injecting will rebuild an ApplicationContext per test which could slow you tests if you have too many @Test methods.

Categories : Java

Concurrency control with method invocation in EJB bean vs. Spring bean
EJB declarative concurency management applies only to singleton session beans, see javax.ejb.ConcurrencyManagement API. Regular session beans have no thread safety issues because containter insures that only one thread accesses a bean instance at any given time. As for Spring beans concurrency is not managed by container, programmers themselves should take care of it.

Categories : Java

Spring bean scope as the class of the bean its autowired
U can use prototype scope. Then it will inject new instance of Executor when the Bean is constructed. So Executor starts its lifecycle when the bean is created. scoped-proxy=target-class creates CGLIB wrapper around your bean. So other beans holds reference only to this wrapper, and the right bean with right scope is dynamically injected into this wrapper. i.e. you don't hold very old expired request scoped bean in your session scoped bean, probably injected when the session was created . Instead new bean for current request is injected every time new request is created. This way you can access beans whith shorter life from beans with longer life i.e. your request scoped bean from your session scoped bean.

Categories : Spring

How to inject a JSF bean into a spring bean
If you are using Spring MVC, you can make your "bean" a Model Attribute, then have it auto-loaded into session using a combination of annotations on the Controller, handler methods, and a method that creates an instance of your bean. Your controller would look something like this: @Controller @SessionAttributes({"myBean"}) @RequestMapping("/myPath") public class MyController { @RequestMapping("/myPath2") public String myHandler(@ModelAttribute("myBean") MyBean myBean) { // ...do stuff, return view } @ModelAttribute("myBean") MyBean createMyBean() { // Create and init an instance return new MyBean(); } } You will get a MyBean magically created for you whenever there isn't one, and any time you update the Model (or ModelAndView) with "myBean", it will also get ma

Categories : Spring

Can a bean be a value to another bean in the Spring Framework?
You can reference a bean like your dataSource. Your class should have a member that can hold the dataSource: package mypackage; public class MyBean { private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = data.Source; } } Then you can inject the dataSource bean into this bean: <beans> <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource"> <!-- set properties --> </bean> <bean id="myBean" class="mypackage.MyBean"> <property name="dataSource" ref="dataSource"/> </bean> </beans> That's it.

Categories : Java

Spring Security Use Bean For Access Configuration Attribute
Having development (or test) specific code/pages in production is always a no-go in my book, but that is, as said, my book :). The access attribute is parsed and may contain a SpEL expressions. The sample code you posted is almost correct, simply prefixing it with a @ should make it work security:http use-expressions="true"> <security:intercept-url pattern="/devlogin.html" access="@someBean.isNotProduction()" /> </security:http> This should work in in Spring Security versions 3.0 and up. Possible related answer, although that is for method security.

Categories : Java

Confuse of Spring Xml config bean and Annotation config bean
You created two versions of one bean - one defined in applicationContext and one in dispatcherServlet. That usually wrong. As you suggest PlaceHolderConfigurer not shared beetween parent/child context. It works only for context where it defined.

Categories : Spring

Singleton Bean in EJB 3.0 not referenced from another Ejb in a different Jar file
You can change the order of the module deployment by specifying it in application.xml. <initialize-in-order>true</initialize-in-order> <display-name>Example</display-name> <module> <ejb>persist.jar</ejb> </module> <module> <ejb>ExampleEAR.jar</ejb> </module> <module> <web> <web-uri>Example.war</web-uri> <context-root>Example-war</context-root> </web> </module> In EJB 3.1, there is support for initializing dependent components using @DependsOn annotation.

Categories : Misc

Request scoped field in a Singleton bean
You can try defining single SampleState request scope bean and then use spring's lookup method to inject this bean wherever you want to.That's works just fine with prototype-scope beans. Fingers crosses it would work with request scope as well. AFAIK, there is no annotation support for lookup method as of now, so either use it's xml vis-a-vis or have a look at javax.inject.Provider relevant question here

Categories : Java

How to handle concurrency with an asynchronous singleton bean
Try this. class X { private void sendStuffToVPN(){ VPNClient client = new VPNClient(); // call the async connect method new Thread(new Runnable(){ public void run() { client.connect(); } }).start(); // wait for connect (or exception and stuff in original source) while(!client.isConnected()){ // wait for connection to be established Thread.sleep(5000); } } }

Categories : Java

Singleton bean: bussiness method invocation
The default lock type in case of container-managed concurrency on the business methods of a singleton session bean is LockType.WRITE which means that when a client of the SSB invokes one of the methods, the SSB will be locked to other clients. That is, no one else can invoke any business methods on the SSB until it finishes serving the actual client. Therefore, clients can only be served one after the other, in a serialized fashion. Further reading: Java EE tutorial

Categories : Java

Spring @Value does not inject property of one bean into another bean's property
You can inject bean A to B and then use @PostConstruct to set bP: @Component public class B { private boolean bP; @Autowired private A a; @PostConstruct public void postConstructMenthod() { bP = a.getAP(); } }

Categories : Spring

Dozer Singleton Startup Bean injetced as Null
It turns out that the CDI spec does not allow a singleton to be injected into a generic type class. So I wrote a lazy initialization of a static final dozer instance. I added the following two methods to the DozerInstantiator: public static DozerBeanMapper getInstance(){ return MapperHolder.instance; } private static class MapperHolder{ static final DozerBeanMapper instance = new DozerBeanMapper(mappingList); } It is then called in the generic type class : DozerInstantiator dozerInstantiator = new DozerInstantiator(); try{ mapper = dozerInstantiator.getInstance(); }catch(Exception e){ log.error("Failed to initialise singleton Dozer bean"); }

Categories : Java

@ManagedProperty - access properties Injected from one view scoped bean into another view scoped bean
I have injected one request scoped bean into another view scoped bean You're not allowed to inject a bean into another bean of a wider scope. As a rule, the following abominations are not allowed :) @RequestScoped >> @ViewScoped @ViewScoped >>@SessionScoped @SessionScoped >> @ApplicationScoped EDIT (Based on your update): Injecting a property of a bean, as against injecting the bean itself, will result in a static injection. The static injection means that the value that's injected into the target is what's available as at the time of injection. As a the time the following line was executed: @ManagedProperty(value="#{selectOfferMpans.selectedSites}") selectedSites is null. So what you should be doing there instead is injecting the entire bean @ManagedProperty(value="#{sele

Categories : JSF

Cant access property of managed bean from another managed bean
It's not possible to access an injected dependency in the constructor. You're basically expecting that Java is able to do something like this: SecondBean secondBean; // Declare. secondBean.firstBean = new FirstBean(); // Inject. secondBean = new SecondBean(); // Construct. It's absolutely not possible to set an instance variable if the instance is not constructed yet. Instead, it works as follows: SecondBean secondBean; // Declare. secondBean = new SecondBean(); // Construct. secondBean.firstBean = new FirstBean(); // Inject. Then, in order to perform business actions based on injected dependencies, use a method annotated with @PostConstruct. It will be invoked by the dependency injection manager directly after construction and dependency injection. So, just replace public SecondBe

Categories : JSF

Why does rich:inputNumberSlider does not update backing bean (@Managed Bean)
The setSecurityLevel setter will never be invoked till you submit the form where your rich:inputNumberSlider is contained. Alternatively, you can set the value whenever the inputNumberSlider is changed, adding an ajax per event processing, which will execute your component (I don't use richfaces, but that would be the desired format): <h:form> <rich:inputNumberSlider id="severityLevel" value="#{pubController.severityLevel}" minValue="1" maxValue="3" maxlength="1" > <a4j:ajax event="change" execute="@this" /> </rich:inputNumberSlider> </h:form> Generally, that kind of behaviour is unrequired unless you want to perform some kind of validation while user is changing the input value (it also could be useful to render dependent componen

Categories : JSF

Dynamically adding a list of bean references to bean definition
Take a look at org.springframework.beans.factory.support.ManagedList That's what <util:list/> uses to compile a list. Create a ManagedList as your variable "checks" and set that object as the property value.

Categories : Spring

Bean creation Exception after running JUnit test while same bean configuration runs without failure in Application Server
Form previous discusion: Annotate the test class with Runner and ContextConfiguration @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:mock-spring-Context.xml") public class MySpringTest { // TODO tests }

Categories : Java

After JPA Reverse Engineer - No unique bean of type [javax.persistence.EntityManagerFactory] is defined: expected single bean but found 0
You are missing declaration of mona-contenxt.xml in web.xml and instead declared mona-mvc.xml twice. The change can be something like this: <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:mona-context.xml</param-value> </context-param>

Categories : Java

getting error No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2
I had the same issue today. Solved it doing the following: First I've added the parameter unitName to @PersistenceContext to both entity manager properties: @PersistenceContext(unitName="appPU") @Qualifier(value = "appEntityManagerFactory") private EntityManager appEntityManager; @PersistenceContext(unitName="managerPU") @Qualifier(value = "managerEntityManagerFactory") private EntityManager managerEntityManager; And in my configuration file I've added a property persistenceUnitName to my bean definitions: <bean id="appEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource1" /> <property name="persistenceUnitName" value="appPU" /> <property name="packagesToScan" val

Categories : Spring

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'helper' . No unique bean of type [java.lang.String]
Try Droping the @Autowired annotation in Ctor and configuring it in xml: <bean id="helper" class="test.Helper"> <constructor-arg ref="clientFactory" /> <constructor-arg ref="modelManager" /> <constructor-arg type="java.lang.String" value="http://test.com" /> <constructor-arg ref="securityService" /> </bean>

Categories : Java

@Singleton bean failed to initialize because of not expected transaction status 4 when it's marked TransactionAttribute=NOT_SUPPORTED
N.B. This was not originally an answer but just some more useful info in digging in to find answers to such problems as there really isn't much on-line in this area. After some additional effort, the cause and an answer have since been found. The answer has been left in its original format with new findings documented as edits and debug help left in-tact to hopefully ease the debugging of others with similar issues. This is a dark place. Well, still no firm answer to the above issue and the problem seems to have gone away. I have found though (looking at a different NoSuchEJBException issue) that the underlying cause is swallowed by the WLS stack. This is the sensible place to start looking for SingletonBean failed to init NosuchEJBException issues in cases where you don't make it int

Categories : Java

Accessing a Bean Id from another Bean ID that is a class Vaadin
You can use the addNestedContainerProperty method of your BeanItemContainer. container.addNestedContainerProperty("userlevel.level"); You'll find more information under "Nested Properties" in this chapter of the Vaadin book: https://vaadin.com/book/-/page/datamodel.container.html There is also the addNestedContainerBean method if you want to access all fields from UserLevel. AFAIK this method replaces the property with its subproperties.

Categories : Java

How to autowired third part bean to my @Controller bean
The point is how are you configuring the web configuration are you using "WebApplicationInitializer" or web.xml with listener, then in the configuration you can extends WebMvcConfigurerAdapter or use @EnableWebMvc, please check these YT video http://www.youtube.com/watch?v=-pV351E_stM Edit 2: ok did you added @ComponentScan and add package of your controller ? as in video you have to use @ComponentScan

Categories : Xml

ThreadPoolExecutor Future Task -exception with spring bean injection-spring-beans-2.0
The issue isn't with anything coming from java.util.concurrent or weblogic. What weblogic is telling you is that one of its registered threads has been waiting longer then 10 minutes for the get() to return. So why hasn't it returned? That is because the Callable you submitted has not yet returned. You should check the callable you submit to the executor and find out why that is still in the call() method. For instance, if I write something like Weblogic-Thread-1 Future f= e.submit(new Callable(){ public Object call(){ Thread.sleep(700000); return null; } }); Weblogic-Thread-2 f.get(); //will sit here and suspend for 700 seconds So you need to see why the task you submitted has not yet completed.

Categories : Java

Spring JSF integration: how to inject a Spring component/service in JSF managed bean?
@ManagedBean vs @Controller First of all, you should choose one framework to manage your beans. You should choose either JSF or Spring (or CDI) to manage your beans. Whilst the following works, it is fundamentally wrong: @ManagedBean // JSF-managed. @Controller // Spring-managed. public class BadBean {} You end up with two completely separate instances of the very same managed bean class, one managed by JSF and another one managed by Spring. It's not directly clear which one would actually be used in EL when you reference it as #{someBean}. If you have the SpringBeanFacesELResolver registered in faces-config.xml, then it would be the Spring-managed one, not the JSF-managed one. If you don't have that, then it would be the JSF-managed one. Also, when you declare a JSF managed bean spec

Categories : Spring

spring custome events:how to raise an event whenever a property values changed in spring bean
You can use Java's PropertyChangeLister to implement this. Please take a look at Vogel's tutorial on Observer Design Pattern in Java.

Categories : Java

Spring Bean not found for Spring Security RememberMe?
Cannot convert value of type [groovy.util.ConfigObject] to required type [int] for property 'tokenLength' This suggests to me that you don't have a grails.plugins.springsecurity.rememberMe.persistentToken.tokenLength property set in your grailsApplication.config - when you ask a ConfigObject for a non-existent key what it returns to you is a new empty ConfigObject.

Categories : Java

Passing reference of bean into another bean
Define class B into Spring context <bean id="bb" class="com.abc.B"></bean> Add an A class referance to class B like class B { private A beanA; //setters getters } and inject bean A to bean B in your xml configuration. Modify bean B defination <bean id="bb" class="com.abc.B"> <property name="beanA" ref="aa" /> </bean> My suggestion is not to use xml to define and inject beans. It is really old, use annotations instead.

Categories : Spring

Passing t:savestate bean to another bean
A view scoped bean is tied to the current view. When you change the current view by navigating to a different view, then that different view would get a brand new instance of the view scoped bean. Note that it works also that way in JSF2. Your best bet is to pass the desired data as request parameters in window.open() URL (escape them!), so that the print bean can get them as request parameters (via either managed property or ExternalContext). An alternative, especially if you've rather a lot of data, is to store the bean instance in the session scope under an unique and autogenerated key (e.g. java.util.UUID) and pass that key as request parameter so that the bean associated with the print page can obtain the data from the session scope by that key.

Categories : JSF

spring--Cannot autowire bean
You need the @Autowired annotation on your type attribute, not the name one: public class Product { private int id; private String name; @Autowired private Type type; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void display(){ System.out.println("Id is: "+ id +" Name is: " + name +" Type is: " +type); } } It's not a bad idea to have setters/getters for Type as well, if only for consistency.

Categories : Spring

Spring bean getting confused
The behavior is expected, this is because you have two beans with the exact same name info and the one defined later(in A) is the one which gets created at runtime. The behavior is same as what would have happened with the beans defined using xml. How this happens is best explained by understanding the internals of Spring @Configuration which is explained with the Spring documentation here - http://static.springsource.org/spring-framework/docs/3.2.3.RELEASE/spring-framework-reference/html/beans.html#beans-java-further-information-java-config. In short, even if you call info() method directly in AConfig, it is not actually invoking the method on the real AConfig instance, instead it is invoked on a proxy, which has the logic to make sure that the correct bean instance is returned.

Categories : Java

bean not injecting on spring MVC
You need to add the following to your servlet-context.xml configuration file, you don't need to declare annotated beans in the XML file. <mvc:annotation-driven /> <context:component-scan base-package="com.carloscortina" /> My suggestion would be to download Spring Stool Suite (STS) and create a new spring template project (selecting the MVC template), it will create a runnable project and that way you can see how everything is put together.

Categories : Spring

Spring Bean Scopes
From the spring specs, there are five types of bean scopes supported : 1. singleton(default*) Scopes a single bean definition to a single object instance per Spring IoC container. 2. prototype Scopes a single bean definition to any number of object instances. 3. request Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext. 4. session Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext. 5. global session Scopes a single bean definition to the

Categories : Java



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