Dao层:
接口:
java
复制代码
public interface UserDao {
public void save();
}
实现类:
java
复制代码
@Component //声明为组件(关键)
public class UserDaoIim implements UserDao {
@Override
public void save() {
System.out.println("save");
}
}
xml配置:
XML
复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 包扫描-->
<context:component-scan base-package="包名"></context:component-scan>
</beans>
使用:
java
复制代码
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring的配置文件.xml");
UserDao userDao = (UserDao) applicationContext.getBean(UserDaoIim.class);
userDao.save();
配置类:
java
复制代码
@Configuration //定义为配置类
//@ComponentScan("com.dt")//单个包扫描
@ComponentScan({"com.dt.dao","com.dt.service"})//多个包扫描
public class SpringConfig {
@PostConstruct //初始化时的方法
public void init(){
System.out.println("init");
}
}
使用:
java
复制代码
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
UserDao userDao = (UserDao) applicationContext.getBean(UserDaoIim.class);
userDao.save();
依赖注入:
service接口:
java
复制代码
public interface UserService {
public void save();
}
实现类:
java
复制代码
@Service //注明是service层
public class UserServiceImp implements UserService {
@Autowired //自动注入
private UserDao userDao;
public UserServiceImp() {}
public UserServiceImp(UserDao userDao, Integer number) {
this.userDao = userDao;
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void save() {
userDao.save();
System.out.println("Service_save");
}
}
使用:
java
复制代码
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = applicationContext.getBean(UserServiceImp.class);
userService.save();
读取配置文件:
配置类(添加下面注解):
java
复制代码
@PropertySource("文件")
属性使用(在service接口,添加下面方法):
java
复制代码
void show();
属性使用(在service实现类,添加下面属性):
java
复制代码
@Value("${key}") //配置文件的key,读取该key的value
private String username;
public void show(){
System.out.println("username:"+username);
}
测试:
java
复制代码
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
UserService userService = applicationContext.getBean(UserServiceImp.class);
userService.show();
导入另一个配置类(方式一):
java
复制代码
@Import("另一个配置类")
导入另一个配置类(方式二):1.在主配置类扫描的包包含配置文件的包。2.在另外的配置文件中添加:@Configuration
第三方bean使用@Bean标记。