完全注解开发
- 创建配置类,代替xml配置文件
@Configuration //把当前类作为配置类,代替xml配置文件
@ComponentScan(basePackages = {
"com.demo"})
//等价于<context:component-scan base-package="com.demo.spring5"></context:component-scan>
public class SpringConfig {
}
- 编写测试类
不再使用ClassPathXmlApplicationContext(“地址”)了而是使用AnnotationConfigApplicationContext(SpringConfig.class);
ApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);
public interface UserDao {
public void add();
}
@Repository(value = "userDaoImpl1")
public class UserDaoImpl implements UserDao{
@Override
public void add() {
System.out.println("若是情短,相思漫长");
}
}
@Service
public class User {
@Resource(name="userDaoImpl1")
private UserDao userDao;
@Value(value="abc")
private String name;
public void add(){
System.out.println("service add......."+name);
userDao.add();
}
}
@Test
public void Test01(){
ApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);
User user=context.getBean("user", User.class);
System.out.println(user);
user.add();
}
/**
com.demo.spring5.service.User@3e92efc3
service add.......abc
若是情短,相思漫长
*/