Spring框架IOC

idea配置tomcat,jetty服务器插件

pom.xml 添加插件

<build> 
    <plugins>
        
        <plugin> 
            <groupId>org.apache.tomcat.maven</groupId> 
            <artifactId>tomcat7-maven-plugin</artifactId> 
            <version>2.2</version> 
        </plugin>
        
        <!--jetty --> 
        <plugin>
            <groupId>org.eclipse.jetty</groupId> 
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.4.20.v20190813</version> 
        </plugin>
        
    </plugins>
</build>

Spring框架环境搭建

pom.xml添加spring框架坐标依赖

	<!--
        添加Spring 坐标
    -->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.9.RELEASE</version>
    </dependency>

Spring Ioc 实例化 bean 对象的三种方式

一.构造器实例化(默认)
构造器必须存在 不存在 出现异常
xml配置
<bean id="userServiceImpl" class="com.jt.service.impl.UserServiceImpl"></bean>
二.静态工厂(了解)
定义静态工厂
public class StaticFactory {
    public static UserDao getUserDao(){ 
        System.out.println("实例化静态工厂 返回userDao..."); 	
        return new UserDao(); 
    }
}
xml配置
<!-- 配置bean 使用bean 标签 --> 
<bean id="userDao" class="com.jt.factory.StaticFactory" factory-method="getUserDao"> </bean>
测试

对象仍然为单例对象

三.实例化工厂(了解)
工厂定义
public class InstanceFactory { 
    public AccountDao getAccountDao(){ 
        return new AccountDao(); 
    } 
}
xml配置
<!-- 
    实例化工厂 
    	首先配置实例化工厂bean 对象 
    	再配置业务bean 
    		factory-bean:实例化工厂
    		id factory-method:实例化工厂方法 
--> 
<bean id="instanceFactory" class="com.jt.factory.InstanceFactory">
</bean> 
<bean id="accountDao" factory-bean="instanceFactory" factory-method="getAccountDao" ></bean>

Spring IOC 手动装配(注入)

set(方法) 推荐使用

内部实现通过反射

java代码

public class UserService { 
    private UserDao userDao ; 
    public AccountDao accountDao; 
    private String host;
    private Integer port; 
    public void setPort(Integer port) { 
        this.port = port; 
    }
    
    public void setHost(String host) { 
        this.host = host; 
    }
    
    public void setAccountDao(AccountDao accountDao) { 
        this.accountDao = accountDao; 
    }
    
    public void setUserDao(UserDao userDao) {
		this.userDao = userDao; 
    }
    
    public UserService() {
        
    }
    
    public void test(){ 
        userDao.test(); 
        accountDao.test(); 
        System.out.println("hello spring"); 
    } 
}

xml配置

<bean id="userService" class="com.shsxt.service.UserService"> 
    <!--
        Set 注入使用Property标签: 
       	  name:业务对象属性名 
       	  ref: 某一个bean 的id 值 
          value:给基本类型 常用对象(String 日期) || 集合 
	-->
    <property name="userDao" ref="userDao"></property> 
    <property name="accountDao" ref="accountDao"></property> 
    <property name="host" value="192.168.1.190"></property> 
    <property name="port" value="25"></property> 
    
</bean>

<bean id="userDao" class="com.jt.dao.UserDao"></bean> 
<bean id="accountDao" class="com.jt.dao.AccountDao"></bean>
Set 注入实现集合装配

java代码

private List<String> list; 
private Set<String> ss; 
private Map<String,Object> map; 
private Properties properties; 

public void setProperties(Properties properties) {
	this.properties = properties; 
}

public void setMap(Map<String, Object> map) { 
    this.map = map;
}

public void setSs(Set<String> ss) {
    this.ss = ss; 
}

public void setList(List<String> list) { 
    this.list = list;
} 

 public void printList(){
        list.forEach(s -> {
            System.out.println(s);
        });
  }

 public void printSet(){
        ss.forEach(s -> {
            System.out.println(s);
        });
    }

 public void printMap(){
        map.forEach((k,v)->{
            System.out.println(k+","+v);
        });
    }

 public void printProperties(){
        for (Map.Entry<Object, Object> objectEntry : properties.entrySet()) {
            System.out.println(objectEntry.getKey() + "," + objectEntry.getValue());
        }
    }

XML 配置

<bean id="userService" class="com.jt.service.UserService">
        <!--
            Set 注入使用Property标签:
                name:业务对象属性名
                ref: 某一个bean 的id 值
        -->
        <property name="userDao" ref="userDao"></property>

        <property name="accountDao" ref="accountDao" ></property>
        <property name="host" value="192.168.1.190"></property>

        <property name="port" value="25"></property>

        <!--
           list 集合装配
        -->
        <property name="list">
            <list>
                <value>上海松江</value>
                <value>上海浦东</value>
                <value>上海徐汇</value>
            </list>
        </property>

        <!--
          set 注入
        -->
        <property name="ss">
            <set>
                <value>杭州</value>
                <value>苏州</value>
                <value>八宝粥</value>
            </set>
        </property>


        <!--
           map 注入
        -->
        <property name="map">
            <map>
                <entry>
                    <key>
                        <value>上海</value>
                    </key>
                    <value>环球金融中心</value>
                </entry>
                <entry>
                    <key><value>杭州</value></key>
                    <value>西湖</value>
                </entry>
                <entry>
                    <key><value>苏州</value></key>
                    <value>园林</value>
                </entry>
            </map>
        </property>
        
        <property name="properties">
            <props>
                <prop key="a">10</prop>
                <prop key="b">abc</prop>
                <prop key="c">test</prop>
            </props>
        </property>

    </bean>

构造器

java代码

private AccountDao accountDao; 
private RoleService roleService; 
private String aname; 

public AccountService(AccountDao accountDao, RoleService roleService, String aname) { 
	this.accountDao = accountDao; 
	this.roleService = roleService;
	this.aname = aname;                                                                                                                                                                       		
}

xml代码

<bean id="accountService" class="com.jt.service.AccountService"> 
    <!--
		构造器注入 constructor-arg 
			name:业务对象属性名 
			ref: 某一个bean 的id 值 
			value:基本类型 常用类型String|日期 
	--> 
    <constructor-arg name="accountDao" ref="accountDao"></constructor-arg>
    <constructor-arg name="roleService" ref="roleService"></constructor-arg> 				<constructor-arg name="aname" value="admin" ></constructor-arg> 

</bean>
使用构造器注入有可能出现相互引用的问题

静态工厂(了解)

实例化工厂(了解)

Spring IOC自动化装配及自动扫描管理Bean(注入)

IOC 帮助应用程序实现属性的自动化注入 具体配置借助注解

环境调整:

XML 配置 引用命名空间 context

* 自动化装配注解(反射): 
* @Resource: 
* 	默认按照属性名称实现装配 如果属性名未找到按照类型(Class类型)装配 
* 	属性可以提供set 方法 也可以不提供set 方法 
* 	声明在属性级别 或者set方法级别 
* 	如果显式声明name 属性 ioc 实现装配时必须按照name 属性进行查找bean 对象 如果未找到报错 
* 	name 的使用在接口注入时 如果接口仅有一个实现 可以省略name 属性 如果接口存在多个实现 必须声明name值

spring.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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!--
       配置扫描包范围   应用程序业务对象
        base-package:包路径
    -->
    <context:component-scan base-package="com.jt"/>
</beans>
/**  一丶IOC 对象的依赖注入:
	 自动化装配注解
     * 1.@Resource
     *      声明级别:类级别  属性级别  方法级别  常用 属性(推荐) | 方法(Set 方法)
     *      装配规则:
     *          默认按照属性名装配
     *          如果属性名对应的Bean 对象未找到 使用类型(Class 类型)实现装配
     *          如果显式的声明Resource 的name 的value 值 内部装配按照value 执行装配  如果存在该value 对应的对象装配成功 如果不存在装配失败
     *          如果接口存在多个实现时 需要显式的声明name 的value ,根据value 实现装配
     *
     *2.@Autowired
     *     声明级别:常用 属性级别(推荐)  构造器  set
     *     装配规则:
     *        默认按照class 类型执行装配
     *        如果按照名称实现装配  可以配合Qualifier 注解 声明value 值
	 *
	 	 二丶IOC扫描器配置:
	 *	 java 代码
	 *         注解配置(类级别)(标识给IOC当前某一个类需要被实例化)
	 *            持久层(dao层):@Repository
	 *            业务层(Service):@Service
	 *            视图层|控制层(Controller):@Controller
	 *            组件:@Component
	 *
	*/

Bean的作用域及生命周期问题

<!--
       lazy-init:懒加载
           默认false  当ioc 启动时 内部对bean 对象进行实例化
           如果为true  当ioc 启动时 内部不会对bean 对象进行实例化  当获取bean 对象时才会进行实例化 对象仅被实例化一次  单例

         lazy-init 默认值为false:
              1.提前发现应用潜在的配置问题
              2.提供应用程序执行效率

         什么样的对象适合作为单例对象???
              无状态Bean 适合作为单例对象-不存在引起对象状态变化的成员变量
              有状态Bean 不适合作为单例对象-存在引起对象状态变化的成员变量

        作用域分类
             单例作用域(默认)
             原型域(scope="prototype"):每次获取 ioc 会重新实例化bean 对象  了解
             web 作用域
                request 作用域  每一次请求ioc 建立request 域的bean
                session 作用域  每一次有效会话
                GlobalSession(了解) 类似session

         Bean 生命周期
             定义
             初始化
                 init-method:方法名
                 实现接口InitializingBean
             使用阶段
             销毁

         IOC-控制反转与依赖注入:应用程序产生对象的过程转交给外部容器(IOC  充当工厂角色)来负责产生  属性赋值交给ioc 实现

-->

Spring IOC定时调度

配置quartz.xml

cron表达式可以利用网页在线cron表达式编辑
<?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"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task.xsd">

    <!--
       配置扫描包范围   应用程序业务对象
    -->
    <context:component-scan base-package="com.jt"/>


    <!--
       定时任务配置
           1.注解
           2.xml
    -->
   <!-- <task:annotation-driven/>  基于注解-->

    <task:scheduled-tasks>
        <task:scheduled ref="jobService" method="job01" cron="0/2 * * * * ?"/>
        <task:scheduled ref="jobService" method="job02" cron="0/5 * * * * ?"/>
    </task:scheduled-tasks>
	<!--基于xml-->
</beans>

java代码

@Service
public class JobService {

    //@Scheduled(cron = "0/2 * * * * ? ") 基于注解配置
    public void job01(){
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"-->job01-->hello world");
    }

   // @Scheduled(cron = "0/5 * * * * ? ") 基于注解配置
    public void job02(){
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"-->job02-->hello world");
    }

}

测试

public class Quartz {

    public static void main(String[] args) {
        new ClassPathXmlApplicationContext("quartz.xml");
        //加载xml,ioc启动,自动扫描JobService,JobService被实例化,ioc根据注解@Scheduled定时调度job方法
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值