Why does Spring Boot have #ConditionalOnMissingBean(name = "kafkaListenerContainerFactory")? - spring-kafka

about KafkaAnnotationDrivenConfiguration
Why exactly the condition by name? because of this, several bins appear in the context.

The kafkaListenerContainerFactory name is used in the KafkaListenerAnnotationBeanPostProcessor:
/**
* The bean name of the default {#link org.springframework.kafka.config.KafkaListenerContainerFactory}.
*/
public static final String DEFAULT_KAFKA_LISTENER_CONTAINER_FACTORY_BEAN_NAME = "kafkaListenerContainerFactory";.
Since we cannot use a dependency injection for BeanPostProcessor, there is a convention in spring-kafka to just specify a bean name which has some default. So, by convention Spring Boot auto-configures one specific for us.
Not sure what is your concern about several beans, but you indeed can have configured #KafkaListener for specific containerFactory and not rely on a default one.

Related

What does it mean when saying "to be assigned something"| ASP.NET Core

I was reading a book about Learning ASP.NET Core API when I run to a part saying:
We create a private read-only field _repository that will be assigned
the injected MockCommandAPIRepo object in our constructor and used
throughout the rest of our code.
Here is some text I thought you'd better have:
Then there are some explanations related to the picture above:
Add the new using statement to reference ICommandAPIRepo.
We create a private read-only field _repository that will be assigned the injected MockCommandAPIRepo object in our constructor
and used throughout the rest of our code.
The Class constructor will be called when we want to make use of our Controller.
At the point when the constructor is called, the DI system will spring into action and inject the required dependency when we ask for
an instance of ICommandAPIRepo. This is Constructor Dependency
Injection.
We assign the injected dependency (in this case MockCommandAPIRepo) to our private field (see point 1).
And that’s pretty much it! We can then use _repository to make use of our
concrete implementation class, in this case MockCommandAPIRepo. As
I’ve stated earlier, we’ll reuse this pattern multiple times through
the rest of the tutorial; you’ll also see it everywhere in code in
other projects – take note.
Now, According to the highlighted part above in number 2, I got a little confused!
I've heard of "to be assigned by some value" before, but here, it is saying that:
that will be assigned the injected MockCommandAPIRepo object in our constructor
and as you see, there is no "by" added before the injected MockCommandAPIRepo object....
So, I have a question now. What does it mean by the highlighted part above in number 2?
Does it mean the same when we add "by" in the sentence? or not?
This is about dependency injection in Asp.Net Core. After we register service to the IOC Container, How to use it in our controller? We can inject them in controller via Constructor Injection. Once we register a service, the IoC container automatically performs constructor injection if a service type is included as a parameter in a constructor. In your question, An IoC container will automatically pass an instance of ICommandAPIRepo(MockCommandAPIRepo) to the constructor of CommandsController. Now we can use MockCommandAPIRepo in the constructor. But it can only be used in constructor, How can we use it in other method in CommandsController? Here we use:
private readonly ICommandAPIRepo _repository;
to create a global variable in CommandsController, Then in constructor, We use:
_repository = repository
assign the value of repository to _repository. Now _repository and repository has the same value, Because _repository is a global variable, So We can use _repository in other method in CommandsController. The whole process of dependency injection is done.

How Can I make Spring-MVC #PropertySources load first, before any other configuration

I have a spring-mvc application that is using java configuration, not xml. There are #Configuration annotations sprinkled through several files. In particular, there is a #PropertySources annotation in one file in a class that implements WebMvcConfigurerAdapter. There are two classes which contain an #Autowired Environment variable. One of these classes is itself a #Configuration class, and I would like it to have access to the fully-loaded Environment at the time it runs.
This isn't happening. When this code executes, the Environment is still null. I've tried reordering the #ComponentScan packages, tried moving the #PropertySources annotation, and nothing has helped me load the property sources in time.
I want this to happen first, before any other configuration.
What must I do to make it so?
UPDATE: After trying many things, including the Order annotation, I find the problem seems to be not so much that the #PropertySources are being loaded too late as that a class I have that is derived from org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer is being loaded too soon. Nothing in my code even references this class but Spring is somehow deciding that this, above all other classes, must be initialized first. No amount of messing around with #Order seems to change this. This in spite of the javadocs, which indicate that the behavior I want is the default:
Caveats
Subclasses of AbstractDispatcherServletInitializer will register their
filters before any other Filter. This means that you will typically
want to ensure subclasses of AbstractDispatcherServletInitializer are
invoked first. This can be done by ensuring the Order or Ordered of
AbstractDispatcherServletInitializer are sooner than subclasses of
AbstractSecurityWebApplicationInitializer.
You can use ContextInitializer, catch the moment when Boot prepared its environment and "inject" your property source programmatically as you want.
If you have a ConfigurableApplicationContext then it provides a ConfigurableEnvironment, which contains the propertySources as a list. If you want your PropertySource to rule all above the others than add it as first. If you want to place it to a special position then you can add it before an other, identified by its "name".
public class ConfigInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
#Override
public void initialize(ConfigurableApplicationContext ctx) {
// rule over all the others:
ctx.getEnvironment().getPropertySources().
addFirst(new ResourcePropertySource("file:/etc/conf/your_custom.properties"));
// rule over application.properties but not argument or systemproperties etc
ctx.getEnvironment().getPropertySources().
addBefore("applicationConfig: [classpath:/application.properties]",
new ResourcePropertySource("classpath:your_custom.properties"));
// names can be discovered by placing a breakpoint somewhere here and watch
// ctx.getEnvironment().getPropertySources().propertySourceList members,
// each has a name ...
}
}
You can bring into play this class by:
registering it in the application.properties :
context.initializer.classes=a.b.c.ConfigInitializer
or from application start :
new SpringApplicationBuilder(YourApplication.class).
initializers(new ConfigInitializer()).
run(args);
By the way this is a proper way to inject more of your custom properties, like properties coming from a database or a different host etc...
Not that I am an expert in Java config but maybe:
Spring 4 utilizes this feature in its #PropertySource annotation. To
remind you, #PropertySource annotation provides a mechanism for adding
a source of name/value property pairs to Spring's Environment and it
is used in conjunction with #Configuration classes.
Taken from: http://blog.codeleak.pl/2013/11/how-to-propertysource-annotations-in.html
Are you using #PropertySource or #PropertySources?
Have You tried 'order' property for spring bean initialisation?

#Specializes for EJB

I'm trying to specialize an EJB. I have
package com.foo.core;
#Stateless
public class MyFacade { }
and
package com.foo.extension;
#Specializes
#Stateless
public class MyFacade extends com.foo.core.MyFacade { }
In my opinion, this should work, because the meaning of #Specializes is, that CDI should forget about the core-class and instead use the specialized class. I also found this bug https://issues.jboss.org/browse/WELD-1451 which indicates, that it is possible to specialize an EJB.
But if i try to deploy my application (I'm using Weblogic 12.1.3), I always get
weblogic.utils.ErrorCollectionException: There are 1 nested errors:
weblogic.j2ee.dd.xml.AnnotationProcessException: Duplicate ejb name
'MyFacade' found: annotation 'Stateless' on bean class
com.foo.core.MyFacade and annoation 'Stateless' on bean class
com.foo.extension.MyFacade
Am I doing anything wrong?
Thanks!
The exception message you quoted is caused by a name conflict, which is not directly related to CDI at all: each EJB can be addressed by a number of different JNDI names, and some of them (e.g. java:module/MyFacade) only include the simple class name, not the package name. So you cannot have two EJBs with the same name in different packages.
Adding CDI and #Specializes may prevent the specialized EJB from showing up in the CDI container, but it is still an EJB.
You can try to rename your derived class - this should solve the duplicate name issue, but I'm not sure it will solve your overall problem.

Automatic Localization in symfony2

Please look at the following code:
public function __construct($error_code)
{
$translator = new Translator('en');
$translator->addLoader('yaml', new YamlFileLoader());
$translator->addResource('yaml', dirname(__DIR__).'/Resources/translations/messages.en.yml', 'en');
$this->setErrorCode($translator->trans($error_code));
}
I am new to symfony. I have created a class MyProjectExceptions which extends Exception. Now when I have to throw a custom exception I call this class where I get the $error_code. Now this $error_code is a constant of another class which has its locale in MyBundle/Resources/transalations/messages.en.yml which will be used to throw as exception message.
Now my question are following:
How can I avoid addResource, so it can automatically add it based on Locale and find the string?
How to access serviceContainer in this class so that I can access session to set and get locales OR other services.
Can we set the default Loader as well.
In above code I am creating an instance of Translator class and manually passing 'en'. but it should pick default locale or user set locale.
I tried many solutions but not able to get the desired results.
Any help would be appreciated. Thanks in advance.
You need to register your class as Symfony service. Read the documentation: http://symfony.com/doc/current/book/service_container.html#creating-configuring-services-in-the-container
After that you can inject other services (like Translation) in your constructor. It will use all parameters that you have already set.
If you inject translator service it will pick the parameters that you have already set. For example, if you defined parameters for translator (including default locale) at config.yml, then you overrode this locale with parameter in route, you will get translator service set up with this locale. And it will automatically use resources that are lied in appropriate directories.

Passing state between EJB methods / #RequestScoped and #Stateless

I have a #RequestScoped CDI bean that I want to turn into an EJB to get declarative transactions. (I'm on EJB 3.1, Java EE 6)
Currently, I am passing state between subroutines, under the assumption that the instance is only used in a single request. If I add #Stateless now that assumption would change.
For example, I want to do something like
#Stateless
#Named
#RequestScoped
public class Foo {
private String var1; // can't use instance vars in #Stateless?
private String var2;
public void transactionForRequest() {
var1 = value;
var2 = value;
....
subroutine();
}
}
I assume the above doesn't work- is that correct?
I am contemplating two alternatives:
Use #Stateful instead of #Stateless, along with #Named and #RequestScoped.
Keep #Stateless and use EJBContext.getContextData map to replace instance variables.
Which is better? And is there some other alternative I'm not thinking of? (Besides wait for Java EE 7 or switch to Spring. :-))
While #Stateless, #Singleton and #MessageDriven can have scoped references injected via #Inject, they cannot be #RequestScoped or any other scope. Only the #Stateful model is flexible enough to support scopes. In other words, you can annotate the #Stateful bean class itself as #RequestScoped, #SessionScoped, etc..
In simple terms #Stateless, #Singleton have fixed "scopes" already. #Singleton is essentially #ApplicationScoped and #Stateless would perhaps be some made-up scope like #InvocationScoped, if that existed. The lifecycle of an #MessageDriven bean is entirely up to the Connector that drives it and is therefore also not allowed to have user-defined scope.
See also https://stackoverflow.com/a/8720148/190816
I would go with SFSB instead of SLSB. You want to hold a state, so for me this is the most important information - this is a job for Stateful EJB.
Also I don't think that EJBContext#getContextData() would help you. As far as I remember, it's only valid for a duration of a call. Therefore, each invocation of a method on your EJB will create new context data map (at least it's what I would expect.)
If you are using Stateless beans then you are responsible for any state-management and you would normally do this in the web-app layer using HttpSessions. And yes, you can't use instance variables as stateless beans are pooled.

Resources