Spring5 完全注解开发
原创
©著作权归作者所有:来自51CTO博客作者深漂小码哥的原创作品,请联系作者获取转载授权,否则将追究法律责任
1.创建配置类,替代xml配置文件
package com.leo.spring5.config;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.ComponentScan;
@Configurable // 作为配置类,替代xml文件
@ComponentScan(basePackages = {"com.leo"})
public class SpringConfig {
}
2.编写其他类
package com.leo.spring5.service;
import com.leo.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class UserService {
@Autowired
private UserDao userDao;
public void add() {
System.out.println("service add ...");
userDao.add();
}
}
package com.leo.spring5.dao;
public interface UserDao {
public void add();
}
package com.leo.spring5.dao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl implements UserDao{
@Override
public void add() {
System.out.println("dao add");
}
}
3.测试
package com.leo.spring5.test;
import com.leo.spring5.config.SpringConfig;
import com.leo.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestSpring {
@Test
public void testService() {
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = context.getBean("userService", UserService.class);
System.out.println(userService);
userService.add();
}
}
4.执行