Spring bean configuration method and dependency Injection Method
Bean configuration method: through the full class name (reflection), through the factory method (static factory method & instance factory method), FactoryBean
Configure bean according to the full class name
Dependency injection method:
Property injection:
The applicationContext. xml configuration file is:
Package com. spring;
Public class HelloWord {
Private String userName;
Public void setUserName (String userName ){
This. userName = userName;
}
Public void hello (){
System. out. println (hello: + userName );
}
Public HelloWord (){
System. out. println (construct !!!!!!!!!!);
}
}
Package com. spring;
Import org. springframework. context. ApplicationContext;
Import org. springframework. context. support. ClassPathXmlApplicationContext;
Public class Test {
Public static void main (String [] args ){
/**
* Create an object and assign values to the object to spring.
*/
// HelloWord helloWord = new HelloWord ();
// HelloWord. setUserName (hello );
// HelloWord. hello ();
// 1. Create a spring IOC container
ApplicationContext ctx = new ClassPathXmlApplicationContext (applicationContext. xml );
// 2 obtain the Bean from the container
HelloWord helloWord = (HelloWord) ctx. getBean (helloWord );
// 3. Call the Method
HelloWord. hello ();
}
}
Output result:
Construct !!!!!!!!!!
Hello: springsss
Constructor injection:
The applicationContext. xml file is
Xmlns: p = http://www.springframework.org/schema/p
Xmlns: xsi = http://www.w3.org/2001/XMLSchema-instance
Xsi: schemaLocation = http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans.xsd>
Public class Car {
Private String name;
Private String color;
Private int num;
Public Car (String color, int num ){
Super ();
This. color = color;
This. num = num;
}
@ Override
Public String toString (){
Return Car [name = + name +, color = + color +, num = + num +];
}
}
Package com. spring;
Import org. springframework. context. ApplicationContext;
Import org. springframework. context. support. ClassPathXmlApplicationContext;
Public class Test {
Public static void main (String [] args ){
// 1. Create a spring IOC container
ApplicationContext ctx = new ClassPathXmlApplicationContext (applicationContext. xml );
Car car = (Car) ctx. getBean (car );
System. out. println (car. toString ());
}
}
Output result:
Car [name = null, color = green, num = 22]