前置:
BeanService.java:
public interface BeanService {
void injection();
}
BeanServiceImpl.java:
public class BeanServiceImpl implements BeanService {
private int id;
private String name;
public BeanServiceImpl(){
System.out.println("调用无参构造实例化");
}
public BeanServiceImpl(int id, String name){
this.id = id;
this.name = name;
System.out.println("调用全参构造实例化");
}
public void setId(int id) {
System.out.println("调用set方法注入id");
this.id = id;
}
public void setName(String name) {
System.out.println("调用set方法注入name");
this.name = name;
}
@Override
public void injection() {
System.out.println("[id:" + this.id + ", name:" + this.name+"]");
}
}
Ⅰ.构造函数注入
beans.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="beanService" class="BeanServiceImpl">
<constructor-arg name="id" value="1"></constructor-arg>
<constructor-arg name="name" value="张三"></constructor-arg>
</bean>
</beans>
测试类:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
BeanService beanService = (BeanService) ac.getBean("beanService");
beanService.injection();
}
}
结果:
调用全参构造实例化
[id:1, name:张三]
Ⅱ.set方法注入
beans.xml
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="beanService" class="BeanServiceImpl">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
</bean>
</beans>
结果:
调用无参构造实例化
调用set方法注入id
调用set方法注入name
[id:1, name:张三]
Ⅱ.注解注入
Configuration.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@org.springframework.context.annotation.Configuration
public class Configuration {
@Bean
public BeanService bean() {
return new BeanServiceImpl(1,"张三");
}
}
测试类:
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(Configuration.class);
BeanService beanService = (BeanService) ac.getBean("bean");
beanService.injection();
}
}
结果:
调用全参构造实例化
[id:1, name:张三]