Spring学习1
https://blog.csdn.net/li1376417539/article/details/104951358
https://docs.spring.io/spring- framework/docs/current/reference/html/core.html#
https://www.cnblogs.com/zxcoder/p/11964433.html
https://www.cnblogs.com/zktww/p/11550891.html
- Spring 框架是一个分层架构,由 7 个定义良好的模块组成。Spring 模块构建在核心容器之上,核心容器定义了创建、配置和管理 bean 的方式 .
-------------除此之外---------------
- Spring Boot与Spring Cloud
- 第一个Spring项目
- 创建User类
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
}
- UserDao
public interface UserDao {
void sayHi();
}
- UserDaoImpl
public class UserDaoImpl implements UserDao {
public void sayHi() {
System.out.println("hi,spring");
}
}
- UserService
public interface UserService {
void sayHi();
}
- UserServiceImpl
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void sayHi() {
this.userDao.sayHi();
}
}
- applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.lyb.pojo.User">
<property name="name" value="zhangsan"/>
<property name="age" value="10"/>
</bean>
<bean id="userDaoImpl" class="com.lyb.dao.impl.UserDaoImpl"></bean>
<bean id="userServiceImpl" class="com.lyb.service.impl.UserServiceImpl">
<property name="userDao" ref="userDaoImpl"/>
</bean>
</beans>
注意 :
Spring的Set注入,需要有无参构造器。
- 测试
@Test
public void Test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User) context.getBean("user");
System.out.println(user.toString());
}
@Test
public void TestSayHi(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("userServiceImpl");
userServiceImpl.sayHi();
}
}
- Spring使用有参数构造创建对象
<!--第一种使用下标赋值-->
<bean id="user" class="com.lyb.pojo.User">
<constructor-arg index="0" value="zhangsan"/>
<constructor-arg index="1" value="10"/>
</bean>
<!--第二种通过类型赋值-->
<bean id="user" class="com.lyb.pojo.User">
<constructor-arg type="java.lang.String" value="zhangsan"/>
<constructor-arg type="int" value="10"/>
</bean>
<!--第三种通过名称赋值-->
<bean id="user" class="com.lyb.pojo.User">
<constructor-arg name="name" value="zhangsan"/>
<constructor-arg name="age" value="20"/>
</bean>