使用java配置来代替xml:
这类方式多用于springboot
一、简单配置Bean
配置App:
/**
* Java配置文件
*
* @Configuration 让当前类和applicationContext.xml作用等价
*
**/
@Configuration//该注解是必须的
public class AppContext {
/**
* @Bean 的作用和的作用是一样的
* id name 默认是和方法名相同的
* @return
*/
@Bean("user")
public User getUser() {
// TODO Auto-generated method stub
Dog dog = new Dog("小狗");
User user = new User("张三",dog,13);
/*user.setName("张三");
user.setAge(13);*/
return user;
}
@Bean("dog")
public Dog getDog() {
// TODO Auto-generated method stub
Dog dog = new Dog();
// dog.setName("小狗");
return dog;
}
}
Pojo就是简单的pojo类这里省略
测试:
public class Test {
public static void main(String[] args) {
ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(AppContext.class);
/*Dog dog = (Dog) applicationContext.getBean("dog");
dog.setName("小狗");*/
User user = (User) applicationContext.getBean("user");
/*user.setName("张三");
user.setDog(dog);
user.setAge(13);*/
System.out.println(user);
}
}
二、开启扫描,进行自动配置
配置类:
@Configuration
@ComponentScan(basePackages="com.controller,com.service,com.dao,com.pojo")
public class App {
}
控制层:
@Controller
public class ControllerDemo {
@Autowired//根据类型进行注入如要使用名称进行注入需要加入注解:
@Qualifier
// @Resource//根据名称进行注入
private ServiceImpl s;
public void say(String ss) {
// TODO Auto-generated method stub
s.say(ss);
}
}
Service层
@Service
public class ServiceImpl {
@Autowired
private DAOImpl dao;
public void say(String s) {
// TODO Auto-generated method stub
dao.say(s);
}
}
DAO层
@Repository
public class DAOImpl {
public void say(String s) {
// TODO Auto-generated method stub
System.out.println(s);
}
}
测试:
ApplicationContext applicationContext =
new AnnotationConfigApplicationContext(App.class);
ControllerDemo bean = (ControllerDemo) applicationContext.getBean("controllerDemo");
bean.say("haha");