项目结构
pom
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>
spring.mxl
<?xml version="1.0" encoding="UTF-8"?>
<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="user" class="com.whotw.model.User">
<property name="name" value="lisi"></property>
<property name="age" value="23"></property>
</bean>
</beans>
MyConfig
//相当beans
@Configuration
//扫包时注入bean时只对Controller和Service注解有效
@ComponentScan(basePackages = {"com.whotw"},
includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class, Service.class})}, useDefaultFilters = false)
public class MyConfig {
@Bean
public User user() {
return new User();
}
}
User
public class User {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
UserDao
//标记dao类型的自动注入
@Repository
public class UserDao {
}
UserService
//标记service类型的自动注入
@Service
//测试是否单例
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
//测试是否懒加载
@Lazy(true)
public class UserService {
public UserService() {
System.out.println("初始化对象");
}
}
UserController
//标记Controller类型的自动注入
@Controller
public class UserController {
}
WhotwDemo
public class WhotwDemo {
public static ClassPathXmlApplicationContext classPathXmlApplicationContext;
public static AnnotationConfigApplicationContext annotationConfigApplicationContext;
public static void main(String[] args) {
//测试xml格式
xmlDemo();
//测试注解版本
annotationDemo();
}
public static void xmlDemo() {
classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring.xml");
User user = (User) classPathXmlApplicationContext.getBean("user");
System.out.println(user.getAge());
}
public static void annotationDemo() {
System.out.println("启动成功");
annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
annotationConfigApplicationContext.register(MyConfig.class);
annotationConfigApplicationContext.refresh();
//测试是否注入成功
UserService userService = (UserService) annotationConfigApplicationContext.getBean("userService");
System.out.println(userService);
//测试是否单例
UserService userService1 = (UserService) annotationConfigApplicationContext.getBean("userService");
System.out.println(userService == userService1);
String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();
//测试是否排除某些对象没有注入spring容器
for (String beanName : beanDefinitionNames) {
System.out.println(beanName);
}
annotationConfigApplicationContext.close();
}
}
控制台结果