spring框架学习三(IOC)
实体类
package com.yms.hello;
/**
-
@Author 杨明书
-
@PackageName: com.yms.hello
-
@ClassName: Hello
-
@Description:
-
@Date: 2021/12/29 11:28
*/
public class Hello {
private String str;public String getStr() {
return str;
}public void setStr(String str) {
this.str = str;
}@Override
public String toString() {
return "Hello{" +
"str='" + str + ''' +
'}';
}
}
配置文件
<bean id="hello" class="com.yms.hello.Hello">
<property name="str" value="hello world"></property>
</bean>
测试类
import com.yms.hello.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
-
@Author 杨明书
-
@PackageName: PACKAGE_NAME
-
@ClassName: MyTest
-
@Description:
-
@Date: 2021/12/29 11:40
*/
public class MyTest {
public static void main(String[] args) {
//获取spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//现在我们的对象放在spring中管理
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());}
}
总结:ioc是一种编程思想,一句话,对象由spring创建,管理,装配。
配置文件
<bean id="user" class="com.yms.dao.impl.UserDaoImpl"/>
<bean id="mysql" class="com.yms.dao.impl.UserDaoMysql"/>
<bean id="oracle" class="com.yms.dao.impl.UserDaoOracle"/>
<bean id="t" class="com.yms.service.impl.UserServiceImpl">
<property name="userDao" ref="mysql"></property>
</bean>
测试类
import com.yms.dao.impl.UserDaoImpl;
import com.yms.dao.impl.UserDaoMysql;
import com.yms.dao.impl.UserDaoOracle;
import com.yms.service.UserService;
import com.yms.service.impl.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
- @Author 杨明书
- @PackageName: PACKAGE_NAME
- @ClassName: MyTest
- @Description:
- @Date: 2021/12/29 10:16
*/
public class MyTest {
public static void main(String[] args) {
// UserService userService = new UserServiceImpl();
// userService.getUser();
// UserDaoMysql mysql = new UserDaoMysql();
// mysql.getUser();
// UserDaoOracle userDaoOracle = new UserDaoOracle();
// userDaoOracle.getUser();
//
// UserServiceImpl userService = new UserServiceImpl();
// userService.setUserDao(new UserDaoMysql());
// userService.getUser();
// UserServiceImpl userService = new UserServiceImpl();
// userService.getUser();
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl userService = (UserServiceImpl) context.getBean("t");
userService.getUser();
}
}