Spring #autowired annotation example [closed] - spring

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Can someone explain spring #autowired example which is given in the below tutorials point link?
Whatever id I give in the place of bean id which is "spellChecker" it takes that and injects it. for example instead of bean id="spellChecker" if I give bean id="a" in Beans.xml
Spring auto-wired annotation

Here are some point for autowire functionality and how it is works interally,
1) If your application has two bean for same class then it would not works.for that you have to give same bean name as you given in bean.xml file.
like one bean is -> id = "spellChecker1"
second bean is -> id = "spellChecker2"
now you have to autowired like
bean 1 -> #autowired
private SpellChecker spellChecker1;
bean 2 -> #autowired
private SpellChecker spellChecker2;
2) if your application has only one bean for class then it would automatically detect bean and inject.
In your case application has only one bean id="a" so spring automatically detect that bean for class SpellChecker.

Related

Spring #Autowire on method [duplicate]

This question already has answers here:
#autowired on method in Spring
(4 answers)
Closed 1 year ago.
I've seen in many example the use of #Autowire in spring on a method.
For example in configuration file:
#Component
public class SomeConfigFile{
#Autowire
public void someMethod(SomeBeanInstance someBean){
//bla bla
}
I guess someBean in my example above injected to the method by Spring but when does this method is called? and how calls it?
Marks a constructor, field, setter method, or config method as to be
autowired by Spring's dependency injection facilities. This is an
alternative to the JSR-330 Inject annotation, adding
required-vs-optional semantics.
see https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html

How does DelegatingFilterProxy know which filter to call to delegate the doFilter call? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
From Spring's Java docs, web.xml will usually contain a DelegatingFilterProxy definition, with the specified filter-name corresponding to a bean name in Spring's root application context.
Does DelegatingFilterProxy use reflection to know the name of its object and use this name to find the name of the filterchainproxy bean and thus delegate the request to the correct filterchain class?
(But then won't two beans with the same name result into conflict?)
Does DelegtaingFilterProxy use reflection to know the name of it's
object and use this name to find the name of the filterchainproxy bean
and thus delegate the request to the correct filterchain class ?
Not really. It just query Spring ApplicationContext to return a bean which the name is the same as what configured in <filter-name> , which finally boils down to calling :
Filter filter = applicationContext.getBean(targetBeanName, Filter.class);
Behind the scenes , it does not need to use reflection to get a bean by the bean name as internally Spring will index all Singleton beans by its bean name in a map.So looking up a bean by its name is just a key look up from this map.
But then won't two beans with the same name result into conflict
You are right. That 's why if you define two beans with the same name, Spring will throw exception and it cannot start.

Best way to inject component in Spring with Kotlin [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
For inject a beans with Spring/Kotlin, I know two ways :
Passing it into the constructor :
#Service
open class MyService #Autowired constructor(
#Autowired
val myRepository: MyRepository
)
Using the 'lateinit' keyword :
#Service
open class MyService {
#Autowired
lateinit var myRepository: MyRepository
}
I know the two works, but i'd like to know which one is the best ? Is there some problem I can encounter with one solution and not the other ?
Thank you !
I prefer constructor. Spring no longer requires The #Autowired annotation if there is only one constructor. This way you don't have to make the class open (you do for some Spring things, like #Scheduled but that's another question) or use a var. It's also pretty easy to read.
This is all you need
#Service
class MyService (private val myRepository: MyRepository)

which is better to use and why? abstractapplication context or applicationcontext [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I tried ApplicationContext and AbstractApplicationContext both are working fine.
Whether the only difference between those two is registershutdownhook method calling or anything else. Want to know which is better
AbstractApplicationContext Reference Link
Abstract implementation of the ApplicationContext interface. Doesn't
mandate the type of storage used for configuration; simply implements
common context functionality. Uses the Template Method design pattern,
requiring concrete subclasses to implement abstract methods. In
contrast to a plain BeanFactory, an ApplicationContext is supposed to
detect special beans defined in its internal bean factory: Therefore,
this class automatically registers BeanFactoryPostProcessors,
BeanPostProcessors and ApplicationListeners which are defined as beans
in the context.
A MessageSource may also be supplied as a bean in the context, with
the name "messageSource"; otherwise, message resolution is delegated
to the parent context. Furthermore, a multicaster for application
events can be supplied as "applicationEventMulticaster" bean of type
ApplicationEventMulticaster in the context; otherwise, a default
multicaster of type SimpleApplicationEventMulticaster will be used.
Implements resource loading through extending DefaultResourceLoader.
Consequently treats non-URL resource paths as class path resources
(supporting full class path resource names that include the package
path, e.g. "mypackage/myresource.dat"), unless the
DefaultResourceLoader.getResourceByPath(java.lang.String) method is
overwritten in a subclass.
ApplicationContext Reference Link
Central interface to provide configuration for an application. This is
read-only while the application is running, but may be reloaded if the
implementation supports this. An ApplicationContext provides:
Bean factory methods for accessing application components. Inherited
from ListableBeanFactory. The ability to load file resources in a
generic fashion. Inherited from the ResourceLoader interface. The
ability to publish events to registered listeners. Inherited from the
ApplicationEventPublisher interface. The ability to resolve messages,
supporting internationalization. Inherited from the MessageSource
interface. Inheritance from a parent context. Definitions in a
descendant context will always take priority. This means, for example,
that a single parent context can be used by an entire web application,
while each servlet has its own child context that is independent of
that of any other servlet. In addition to standard BeanFactory
lifecycle capabilities, ApplicationContext implementations detect and
invoke ApplicationContextAware beans as well as ResourceLoaderAware,
ApplicationEventPublisherAware and MessageSourceAware beans.
Structure
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext, DisposableBean
public interface ConfigurableApplicationContext extends ApplicationContext
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,MessageSource, ApplicationEventPublisher, ResourcePatternResolver
ConfigurableApplicationContext declare this signature
/**
* Register a shutdown hook with the JVM runtime, closing this context
* on JVM shutdown unless it has already been closed at that time.
* <p>This method can be called multiple times. Only one shutdown hook
* (at max) will be registered for each context instance.
* #see java.lang.Runtime#addShutdownHook
* #see #close()
*/
void registerShutdownHook();
In summary i suggest to use the AbstractApplicationContext only if you want really get profit of the above features else, is better to use ApplicationContext.

2 beans with same name but in different packages; how to autowire them?

I have an application that has 2 beans with the same name, but which are in different packages. My Spring application fails because it cannot decide on which bean to take. Is there any solution for this? The beans do not currently implement specific interfaces.
See below an edited example of the exception:
Caused by:
org.springframework.context.annotation.ConflictingBeanDefinitionException:
Annotation-specified bean name 'dataTransferHandler' for bean class
[aaaaa.ws.handler.DataTransferHandler] conflicts with existing,
non-compatible bean definition of same name and class
[bbbbb.ws.handler.DataTransferHandler]
You will have to give your beans different names - if multiple beans are defined with the same name, then the one defined later will override the one defined earlier - so in your case only one bean will exist with the name of dataTransferHandler.
You can give these two beans different names, so that both can exist and you can inject in the correct one either using:
#AutoWired #Qualifier("dataTransferHandler")
OR
#Resource(name="dataTransferHandler")
You can give attribute primary="true" to the bean defination you want to have the preference when autowired. But the bean names must be different. There is no solution for same bean name.
At run-time when you will get the autowired class then the primary true bean will get the preference for autowiring. Hope this helps you. Cheers.
I asked another question regarding the same problem, and there is a solution that doesn't require using the #Qualifier annotation: if both of your DataTransferHandler classes have a #Component annotation, you can simply add a String argument to one of their constructions (i.e. #Component("Foo")), and that should solve the problem without needing additional changes.
See User9123's answer on my question for more details.

Resources