Spring

Spring

IOCxml配置文件开发

配置导入依赖

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>5.3.1</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.3.1</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>5.3.1</version>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-autoconfigure</artifactId>
  <version>2.4.0</version>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot</artifactId>
  <version>2.4.0</version>
</dependency>

类型注入

<bean id="stu" class="collectionType.Stu">
<!--        数组类型注入-->
        <property name="courses">
            <array>
                <value>java课程</value>
                <value>数据库</value>
            </array>
        </property>

<!--        list属性-->
        <property name="list">
            <list>
                <value>张三</value>
                <value>小三</value>
            </list>
        </property>

<!--        map属性-->
        <property name="maps">
            <map>
                <entry key="JAVA" value="java"></entry>
                <entry key="PHP" value="php"></entry>
            </map>
        </property>

<!--        set属性-->
        <property name="sets">
            <set>
                <value>MySQL</value>
                <value>Redis</value>
            </set>
        </property>
<!--        list 值是对象-->
        <property name="course">
            <list>
                <ref bean="course1"></ref>
                <ref bean="course2"></ref>
            </list>
        </property>

    </bean>
    <!--        创建多个course对象-->
    <bean id="course1" class="collectionType.Course">
        <property name="cname" value="框架"></property>
    </bean>
    <bean class="collectionType.Course" id="course2">
        <property name="cname" value="架构"></property>
    </bean>
<!--    提取list集合类型属性注入-->
    <util:list id="booklist">
        <value>易筋经</value>
        <value>九阴真经</value>
    </util:list>
<!--scope  singleton单实例 默认单实例 singleton在加载Spring配置文件时候创建对象
           prototype多实例对象,不在加载的时候创建对象,在调用getBean方法的时候创建-->
    <bean id="book" class="collectionType.Book" scope="prototype">
        <property name="list" ref="booklist"></property>
    </bean>
    <bean id="MyBean" class="Shang15.MyBean"></bean>
public class Stu {
    //数组类型属性
    private String[] courses;
    //list类型
    private List<String> list;
    //map类型;
    private Map<String,String> maps;
    //set类型
    private Set<String> sets;
    //学生所学多门课程
    private List<Course> course;

    public void setCourse(List<Course> course) {
        this.course = course;
    }

    public void setSets(Set<String> sets) {
        this.sets = sets;
    }

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

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    public void setCourses(String[] courses) {
        this.courses = courses;
    }

    public void test(){
        System.out.println(Arrays.toString(courses));
        System.out.println(list);
        System.out.println(maps);
        System.out.println(sets);
        System.out.println(course);
    }
}
public class Book {
    private List<String> list;

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

级联赋值

<!--    1.service和dao对象的创建-->
    <bean id="userService" class="Oct29.Service.UserService">
<!--        注入userDao对象
              name属性:类里面属性名称
              ref属性:创建userDao对象bean标签id值
-->
        <property name="userDao" ref="userDao"></property>
    </bean>
    <bean id="userDao" class="Oct29.dao.UserDaoImpl"></bean>

<!--  级联赋值  -->
    <bean id="emp" class="Oct29.bean.Emp">
<!--        设置俩个普通属性-->
        <property name="ename" value="lucy"></property>
        <property name="gender" value=""></property>
<!--        设置对象类型属性-->
        <property name="dept">
            <bean id="dept" class="Oct29.bean.Dept">
                <property name="dname" value="安保"></property>
            </bean>
        </property>
<!--        级联赋值-->
<!--        <property name="dept" ref="dept"></property>-->
    </bean>
<!--    <bean id="dept" class="Oct29.bean.Dept">-->
<!--        <property name="dname" value="财务部"></property>-->
<!--    </bean>-->
public class UserService {
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void add() {
        System.out.println("service add");
        userDao.update();
    }
}

public class Emp {
    private String ename;
    private String gender;
//    员工输入某一个部门
    private Dept dept;
    public Dept getDept() {
        return dept;
    }
    public void setDept(Dept dept) {
        this.dept = dept;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }



    public void add() {
        System.out.println(ename + gender + dept);
    }
}
public class Dept {
    private String dname;
    public void setDname(String dname) {
        this.dname = dname;
    }

    @Override
    public String toString() {
        return "Dept{" +
                "dname='" + dname + '\'' +
                '}';
    }
}

配置后置管理器和自动装配

<!--    配置后置处理器-->
    <bean id="myBeanPost" class="collectionType.MyBeanPost"></bean>

<!--    实现自动装配
        bean标签属性autowire,配置自动装配
        autowire属性值常用俩值
        byName根据名称注入 ,注入值bean的id值和类属性一样
        byType根据属性类型注入 -->
    <bean id="emp" class="autowire.Emp" autowire="byType">
<!--        <property name="dept" ref="dept"></property>-->
    </bean>
    <bean id="dept" class="autowire.Dept"></bean>
public class orders {
    private String oname;

    public orders() {
        System.out.println("第一步 执行无参数构造创建bean实例");
    }

    public void setOname(String oname) {
        this.oname = oname;
        System.out.println("第二步 调用set方法设置属性值");
    }

    //创建执行的初始化的方法
    public void initMethod(){
        System.out.println("第三步 执行初始化方法");
    }
    //创建执行的销毁的方法
    public void destoryMethod(){
        System.out.println("第五步 执行销毁方法");
    }
}
public class MyBeanPost implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化之前执行的方法");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //后置处理器
        System.out.println("在初始化之后执行的方法");
        return bean;
    }
}

设置空值,特殊字符,有参构造注入属性,p名称空间注入

<!-- 设置空值-->
<!--        <property name="author">-->
<!--            <null></null>-->
<!--        </property>-->
<!-- 含有特殊字符
            1.把特殊字符转义&gt;或者&lt;
            2.<![CDATA[]]>
-->
<!--        <property name="author">-->
<!--            <value><![CDATA[<<南京>>]]></value>-->
<!--        </property>-->
    </bean>
<!--    有参数构造注入属性-->
    <bean id="order" class="Orders">
        <constructor-arg name="oname" value="abc"></constructor-arg>
        <constructor-arg name="address" value="china"></constructor-arg>

    </bean>
<!--    p名称空间注入-->
<!--    <bean id="book" class="Book" p:author="jj" p:book="西游"></bean>-->

IOC注解开发

配置类代替xml配置文件

@Configuration //作为配置类,代替xml配置文件
@ComponentScan(basePackages = {"config","service","dao"})//扫描哪些包
public class SpringConfig {

}

开启组件扫描

<!--    开启组件扫描
        1,扫描多个包用逗号隔开
        2,扫描包上层目录-->
    <context:component-scan base-package="service,dao"></context:component-scan>

设置扫描内容

<!--  实例1
      use-default-filters="false"  表示不使用默认filter,自己配置filter
      context:include-filter 设置扫描那些内容
      expression="org.springframework.stereotype.Controller只扫描controller类-->
<context:component-scan base-package="service,dao" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--  实例2
  context:include-filter 设置扫描那些内容
  不扫描controller类-->
<context:component-scan base-package="service,dao" >
    <context:exclude-filter  type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

实体类及测试

@Test
public void testService2(){
    ApplicationContext context=new AnnotationConfigApplicationContext(config.SpringConfig.class);
    UserService userService=context.getBean("userService",UserService.class);

    System.out.println(userService);
    userService.add();
}
//在注解里面value属性值可以省略
//默认值是类名称,首字母小写
//UserService -- userService
//@Component(value = "userService")//<bean id="" class="">

//@Service

@Controller
public class UserService {
    //定义dao
    //不需要添加set方法
    //添加属性注解
    @Autowired //根据类型进行注入
    @Qualifier(value = "userDaoImpl1")  //根据名称注入,多个同类型不知道找哪个,要跟着Autowired一起使用
    private UserDao userDao;

    public void add(){
        System.out.println("service add...");
        userDao.add();
    }
}

AOPxml配置文件开发

反射机制

public class JDKProxy {
    public static void main(String[] args) {
        Class[] interfaces= {UserDao.class};
//        UserDao dao=(UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
//            @Override
//            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                return method.invoke(new UserDaoImp1(),args);
//            }
//        });
        UserDaoImp1 userDao=new UserDaoImp1();
        UserDao dao=(UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces,new  UserDaoProxy(userDao));
        int result=dao.add(1,2);
        System.out.println(result);
        System.out.println(dao.update("asd"));
    }
}
class UserDaoProxy implements InvocationHandler{
    private Object obj;
    //有参数构造的传递
    public UserDaoProxy(Object obj){
        this.obj=obj;
    }

    //增强的逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //方法之前执行
        System.out.println("方法之前执行..."+method.getName()+":传递的参数..."+ Arrays.toString(args));

        //被增强的方法执行
        Object res = method.invoke(obj,args);

        //方法之后
        System.out.println("方法之后..."+obj);


        return res;
    }
}
public class UserDaoImp1 implements UserDao {
    @Override
    public int add(int a, int b) {
        System.out.println("add方法执行嘞");
        return a+b;
    }

    @Override
    public String update(String id) {
        System.out.println("update方法执行嘞");
        return id;
    }
}

配置aopxml

<!--    开启Aspect生成带理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<bean id="user" class="aopanno.User"  ></bean>
<bean id="userProxy" class="aopanno.UserProxy"></bean>
<aop:config>
    <aop:aspect id="aspect" ref="userProxy">
        <aop:pointcut id="cut" expression="execution(* aopanno.User.add(..))"/>
        <aop:after method="after" pointcut-ref="cut"></aop:after>
        <aop:before method="before" pointcut-ref="cut"></aop:before>
    </aop:aspect>
</aop:config>
@Component
public class User {
    public void add(){
        System.out.println("add....");
    }


}
public class UserProxy {

    //相同切入点抽取
    @Pointcut(value = "execution(* aopanno.User.add(..))")
    public void pointdemo(){

    }


    @Before(value = "pointdemo()")
    public void before(){
        System.out.println("before...");
    }
    //最终通知
    @After(value = "execution(* aopanno.User.add(..))")
    public void after(){
        System.out.println("after...");
    }
    //异常通知
    @AfterThrowing(value = "execution(* aopanno.User.add(..))")
    public void afterthrowing() {
        System.out.println("afterthrowing...");

    }
    //环绕通知
    @Around(value = "execution(* aopanno.User.add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("aroundbefore...");
        //被增强的方法执行
        proceedingJoinPoint.proceed();
        System.out.println("aroundafter...");
    }
    //后置通知
    @AfterReturning(value = "execution(* aopanno.User.add(..))")
    public void afterReturning() {
        System.out.println("afterReturning...");

    }
}

AOP注解开发

开启组件扫描

<context:component-scan base-package="aopanno"></context:component-scan>
@Configuration
@ComponentScan(basePackages = {"aopanno"})
@EnableAspectJAutoProxy(proxyTargetClass = true)//默认是false false jdk代理
public class ConfigAop {

}
@Configuration
@ComponentScan(basePackages = {"aopanno"})
public class Aspect {
}

实体类及测试

@Component
@Aspect
@Order(1)//数值越小优先级越高
//增强类
public class UserProxy {

    //相同切入点抽取
    @Pointcut(value = "execution(* aopanno.User.add(..))")
    public void pointdemo(){

    }


    @Before(value = "pointdemo()")
    public void before(){
        System.out.println("before...");
    }
    //最终通知
    @After(value = "execution(* aopanno.User.add(..))")
    public void after(){
        System.out.println("after...");
    }
    //异常通知
    @AfterThrowing(value = "execution(* aopanno.User.add(..))")
    public void afterthrowing() {
        System.out.println("afterthrowing...");

    }
    //环绕通知
    @Around(value = "execution(* aopanno.User.add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("aroundbefore...");
        //被增强的方法执行
        proceedingJoinPoint.proceed();
        System.out.println("aroundafter...");
    }
    //后置通知
    @AfterReturning(value = "execution(* aopanno.User.add(..))")
    public void afterReturning() {
        System.out.println("afterReturning...");

    }
}
@Test
public void testAopanno(){
    ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
    User user=context.getBean("user",User.class);
    user.add();
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值