Spring 4 Create Bean Programmatically - spring-4

I've been looking for a way to add datasources at runtime. I want to move away from defining the datasources in #Configuration class and instead when the app loads i want to dynamically create the datasource beans and inject them into the Spring context. I'm not really sure how I can go about doing that.

This is what I ended up with, not sure if this is the right approach or not, if there is a better way please share.
#Component
class SpringContextListener implements ApplicationListener<ContextRefreshedEvent> {
public void onApplicationEvent(ContextRefreshedEvent event) {
org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://MySQL:3306/test?useUnicode=true&characterEncoding=utf8&maxAllowedPacket=512000");
ds.setUsername("MYUSERNAME");
ds.setPassword("MYPASSWORD");
ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) event.getApplicationContext();
ConfigurableListableBeanFactory bf = ctx.getBeanFactory();
bf.registerSingleton("mysqlDSN", ds);
};
}
This is an example of what I want to do, but I would like to eventually have the ability to dynamically create beans and add them to them to spring rather than writing out config files.

Related

Controller reuse in asp.net mvc

I have a two different projects that are actually two different websites when deployed, say WebA & WebB. The structure of both websites is the same in terms of the controllers and models they use. However, the front end is very different. They each have their own UI and own jquery plugins that work for them.
To reduce code duplication, I am proposing both those projects inherit from controllers in another referenced project[controllerDLL]. ControllerDLL is a project that will have all the logic for calling the business layer and returning json serialized model objects. WebA & WebB will each just have empty controller classes that just inherit from the base project[controllerDLL]. This way I feel the controller code is not duplicated.
Can anyone tell me a better way to achieve controller reuse other than the way I have proposed? Does asp.net mvc 4 provide any built-in way to do this better? Can I use AREAS here productively? Is DotNetNuke something I should look at? Or is my approach the best way forward? I am not looking for the how to move controllers into another project. I just want to know what my options are for achieving controller reuse.
Thanks.
Take a look at this SO question. You could keep all the views in the same project and use a custom view engine to find the views (based off a web.config setting).
For example you could have 2 folders /Views/WebA and /Views/WebB. The custom view engine could look up the web.config setting to find out which folder to use and search for the views there. This way you would not have to duplicate the controller code or move it into a separate project. It will just swap out one presentation layer for another at runtime.
You should be able to achieve this by implementing custom controller factory to instantiate the right controller class based on config settings.
You need to implement the interface System.Web.Mvc.IControllerFactory.The two methods in this interface are:
1.System.Web.Mvc.IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName) - To create the controller instance based on RequestContext and controller name.
2.void ReleaseController(System.Web.Mvc.IController controller) - Release the controller instance
Detailed information about using that interface is available
Since the difference between the two applications are the views, you don't need to have them as separate projects. you could have two sets of views and deploy the same project twice using different settings in the web config. To do this, you'll have to implement your own ViewEngine so that the controller can return the correct right views.
public class AppSettingViewEngine: RazorViewEngine
{
public AppSettingViewEngine()
{
string[] viewLocations = new string[] { };
if (ConfigurationManager.AppSettings["Site"] == "WebA")
{
viewLocations = new[] {
"~/WebB/Views/{1}/{0}.cshtml",
"~/WebB/Views/{1}/{0}.cshtml",
"~/WebB/Views/Shared/{0}.cshtml",
"~/WebB/Views/Shared/{0}.cshtml",
};
}
if (ConfigurationManager.AppSettings["Site"] == "WebB")
{
viewLocations = new[] {
"~/WebB/Views/{1}/{0}.cshtml",
"~/WebB/Views/{1}/{0}.cshtml",
"~/WebB/Views/Shared/{0}.cshtml",
"~/WebB/Views/Shared/{0}.cshtml",
};
}
else
{
//Default Settings
viewLocations = new[] {
"~/Views/{1}/{0}.cshtml",
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.cshtml",
"~/Views/Shared/{0}.cshtml",
};
}
this.PartialViewLocationFormats = viewLocations;
this.ViewLocationFormats = viewLocations;
}
}
Then you register it in your Application_Start as follows
protected void Application_Start()
{
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new AppSettingViewEngine());
}

Symfony2 + inject static class

i'm new here and i hope my question is not too trivial.
I have a package with a static class in it (a Grid Builder) and want to use it in symfony2
So i know about the Class loading and the Service Container but i don't get the Container to work.
The Grid Class is depending on 2 other static classes (one for configuration and one for the SQL Query´s)
The Code to use the class is as following:
$Grid = Grid::get_instance();
$Grid->table('products');
echo $Grid->renderGrid();
And internally the class uses calls like GridConfig::database() - so i Thought maybe i cann simply add all three classes to the Service.yml but that doesn't do anything.
So my question is: How can I inject the Static class in a way that I can use it in the Controller?
Is it Possible and if yes what would be the best Practice case to do it?
Thank you for any help.
Since it is static then there really is no need to inject it. Something like:
$grid = \Grid::get_instance;
Should work. If Grid uses namespaces then you need to add that as well. And you will need to ensure the autoloader can find it.
Of course using globals is kind of frowned up. What you can do is to write your own service to act as a wrapper.
class MyGridService
{
protected $grid;
public function getInstance()
{
if (!$this->grid) $this->grid = \Grid::get_instance();
return $this->grid;
}
}
Add MyGridService to your services.yml file then from the controller you can do:
$grid = $this->get('my_grid_service')->getInstance();
You should define a service that uses a factory method to instantiate the object:
service_name:
class: The\Class\Name\Of\The\Created\Object
factory: [ "Grid", "get_instance" ]
Now you can inject the object into your depending class by injecting the service.
See http://symfony.com/doc/current/components/dependency_injection/factories.html

UOW and repositories in an Entity Framework asp.net application

I have just started reading up on using the repository and unit of work patterns. I am currently trying to use it with Entity Framework in an asp.net web forms application. I do however have a question which I am not sure if I would be able to explain in an easy way.
From what I understand a unit of work is used to encapsulate a business transaction. From the examples I have seen a uow is used in the following manner
businessMethod1()
{
uow u = new uow(); //instantiate unit of work
repository1 rep1 = new repository1(uow); //instantiate repository1
repository2 rep2 = new repository2(uow); //instantiate repository1
rep1.dowork();
rep2.dowork();
u.save(); //save the changes made to the database. (effectively saving changes made
//in both repository classes
}
Now suppose I have a businessMethod2() which is similar to the method described above. Suppose I want to use businessMethod1() from within businessMethod2() what would be the best practice. I would want to share the unit of work so should I pass it as an argument? i.e change the method mentioned above to
businessMethod1(uow u)
{
bool isNew = false;
if (u == null)
{
u = new uow();
isNew = true;
}
repository1 rep1 = new repository1(uow); //instantiate repository1
repository2 rep2 = new repository2(uow); //instantiate repository1
rep1.dowork();
rep2.dowork();
if (isNew)
u.save(); //save the changes made to the database.
}
Is this a proper way of working with this?
I was thinking a better way would be to use a singleton uow. On every page request a new instance of the uow is created and is shared by all the business methods. On a new request a different instance is created. Using a singleton uow would mean i wont have to pass it to any of my business methods and can at the same time share it b/w all my business methods.
Are there any drawbacks of doing this? Also is there a better way to implement this?
One way to solve this problem is to use Dependency Injection. Usually constructor injection is used along side a single point of entry to resolve dependencies.
public class MyBusinessService
{
public MyBusinessService(Repository1 repository1, Repository2, uow u)
{
// assign the params to fields
}
public void businessMethod1()
{
}
public void businessMethod1()
{
}
}
There are many popular DI frameworks out there. Pick what you think works for you.
This is about usage of UoW. If you place usage of UoW into BusinessMethod1 you are saying that it is top level business abstraction (business facade). It should probably not be used by other business operation because it would break its "top level". So if you need to use the logic from BusinessMethod1 in another BusinessMethod2 it is not correct approach to add logic making decision about UoW existence - that breaks separation of concerns. BusinessMethod should handle your application logic not UoW creation. Simplest solution is to refactor your BusinessMethod1 and expose shared functionality as a new method without any dependency on UoW:
public void BusinessMethod1()
{
uow u = new uow();
DoSomeWork();
u.save();
}
private void DoSomeWork()
{
repository1 rep1 = new repository1(uow); //instantiate repository1
repository2 rep2 = new repository2(uow); //instantiate repository1
rep1.dowork();
rep2.dowork();
}
Sure this is only very simple example because your methods still don't follow separation of concerns - they do both logic and object creation. You should handle UoW and repositories creation elsewhere and pass created objects inside. You can use approach mentioned by #Eranga but this refactoring will be still applicable if your method2 wants to call something from method1.
This refactoring approach can be modeled also as low level business services and business facade but it is needed only in big projects. In small projects you can also move interaction with UoW to your "controller" (probably code behind in web forms) because the controller drives application logic and it knows what business methods it wants to call in single unit of work.

Access objects instantiated in Flex app's MXML file in other AS classes

I've got an object declared and instantiated in my Flex application's singular MXML file:
public var CDN:CDNClass = new CDNClass;
I would like to access this same CDN object (and its public methods and properties) in another class declared in a separate .as file as such:
package my.vp
{
import my.media.CDNClass;
public class SyncConnectorManager
{
private function syncMessageReceived(p_evt:SyncSwfEvent):void
{
switch (p_evt.data.msgNm)
{
case "startStream" :
// Play a stream
CDN.parsePlayList(p_evt.data.msgVal);
break;
But when I try to access the public method parsePlayList in the CDN object in a method in the class defined in the .as file, I get the following error:
Access of undefined property CDN
The reason I want to do this is to break up the logic of my application into multiple AS files and have minimal MXML files, probably only one.
Thanks - any help is much appreciated. Perhaps my OOD/OOP thinking is not correct here?
IT depends on your class architecture. For your code to work, the CDNClass instance must be defined and implemented inside your SyncConnectorManager.
Generally, you can always call down into components, but should never call up
One option is to pass the instance ofCDNClass to a variable inside SyncConnectorManager. Add this variable to your SyncConnectionManager class:
public var CDN:CDNClass = new CDNClass;
And at some point do this:
syncConnectorManagerInstance.CDN = CDN;
That way both classes will have access to the same CDN instance and can call methods on it.
Yes, your OOP thinking is not correct here. You should take in mind differences between classes and instances. This line declares a filed in a current class and initiates it with an instance:
public var CDN:CDNClass = new CDNClass;
So current instance of your MXML class (you can think about it as usual AS class with some other notation) has public field. To operate with CDN instance you need something from the following:
Read the value of CDN (as far as it is public) from the instance of your MXML class. You need some reference to it for that.
The instance of your MXML class can have a reference to the instance of SyncConnectorManager and SyncConnectorManager should have a way to inject the value of CDN there. Something like:
Your class:
package my.vp
{
import my.media.CDNClass;
public class SyncConnectorManager
{
private var CDN:CDNClass;
public function SyncConnectorManager(CDN:CDNClass)
{
this.CDN = CDN;
}
private function syncMessageReceived(p_evt:SyncSwfEvent):void
{
switch (p_evt.data.msgNm)
{
case "startStream" :
// Play a stream
CDN.parsePlayList(p_evt.data.msgVal);
break;
In your case SyncConnectorManager class hasn't CDN declared (the problem of the compiler error you mentioned) and instantiated (the problem of NPE even if you just declare field).
As the bottom line I can suggest you to follow ActionScript naming and coding conventions to talk other people and team members about your code :)

Singleton Class in Flex

I have a doubt,.... How would you create a Singleton class in Flex...
Is there any convention like the class name should eb Singleton or it should extend any other class.
How many Singleton class can a project have?
Can anyone say the real time usage of a Singleton class?
I am planning to keep my components label texts in a Singleton class... Is it a good approach.
Can of worms asking about singletons!
There are a few different options about creating singletons mainly due to AS3 not having private constructors. Here's the pattern we use.
package com.foo.bar {
public class Blah {
private static var instance : Blah;
public function Blah( enforcer : SingletonEnforcer ) {}
public static function getInstance() : Blah {
if (!instance) {
instance = new Blah( new SingletonEnforcer() );
}
return instance;
}
...
}
}
class SingletonEnforcer{}
Note that the SingletonEnforcer class is internal so can only be used by the Blah class (effectively). No-one can directly instantiate the class, they have to go through the getInstance() function.
hope I'm not hitting dead horses here :)
(edit: ahh, I'm just repeating phils link)
Gregors singleton implementation does not protect against invoking the constructor with a null value, as in:
var b:Blah = new Blah(null);
You will still have only 1 instance, but invoking the constructor is still possible with the consequences that follows.
If you absolutely must enforce the singleton, the constructor should make sure that the enforcer parameter isn't null.
public function Blah( enforcer : SingletonEnforcer ) {
if(!enforcer){
throw new Error("whoops!");
}
}
You should also be concerned about ApplicationDomain when loading swf files. External swf files that uses the same definitions, may have multiple singleton instances (1 in each separate applicationdomain) if you do not specify that the swf file must be loaded into the existing applicationdomain.
This means that Blah.getInstance() in AAA.swf is not the same instance as Blah.getinstance() in BBB.swf, if AAA.swf loads BBB.swf without a LoaderContext instance that tells the plugin to load BBB.swf into the same ApplicationDomain as AAA.swf
First you can reference a previous question to find out how to create a singleton class. You can find more info from a Yakov Fain presentation as well.
Second question, your project can technology have as may singleton class as you see fit but it will only create 1 instance of each. For example, in the cairngorm architecture you have 3 main singletons: controller, service and model. The number of actual class can very depending on your project.
Finally, A real world solutions would be. You have 2 components that need to talk to each other but you don't want them to know the other exists. Meaning sometimes the components are there and sometimes they are not...so you need them to be loosely coupled. you can uses singletons to pass the data from one component to the other with out "talking" to them directly.
Using singletons is a good approach if you need to pass data around your application from component to component and would like to decouple them from each other.
package com.foo.bar
{
public class MySingleton
{
private static var _instance:MySingleton = new MySingleton;
private var _myName:String;
public static function get instance():MySingleton
{
return _instance;
}
public function set myName(value:String):void
{
_myName = value;
}
public function get myName():String
{
return _myName;
}
}
}
Notice the absence of a constructor here.
Hello you could check out the following of a Flex Singleton Class example on http://www.how-to-code.com/flex/flex-design-patterns/flex-singleton-class.html

Resources