Spring框架之基于注解的容器配置

spring框架学习 - spring IoC 之 基于注解的容器配置补充 接上一篇博客:https://blog.youkuaiyun.com/qq_43605444/article/details/121967321?spm=1001.2014.3001.5502 10.3 使用@Primary 微调基于注解的自动装配 由于按类型自动装配可能会导致多个候选,因此通常需要对选择过程进行更多控制。 实现此目的的一种方法是使用 Spring 的 @Primary 注解。 @Primary 表示当多个 bean 是自动装配到单值依赖项的候选者时,应优先考虑特定 bean。 如果候选中恰好存在一个主 阅读详情

默认情况下,Spring容器中的注解配置没有被打开。因此,在我们使用基于注解的配置之前,我们需要在Spring配置文件中启用它。因此,如果你想在你的Spring应用程序中使用任何注解,请考虑以下配置文件。

<context:annotation-config/>

@Required注解是方法级注解,适用于Bean的setter方法。这个注解简单地表明setter方法必须在配置时被配置为具有依赖注入的值。

@Component

@Component
public class SimpleMovieLister {
    private MovieFinder movieFinder;
    @Required
    public void setMovieFinder(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }
    // ...
}

属性movieFinder必须存在,若注入时为null,会抛NullPointerException异常。

@Autowired

我们可以使用@Autowired来标记Spring将要解析和注入的依赖关系。我们可以在构造函数、Setter或字段注入中使用这个注解。

构造函数注入

class Car {
    private Engine engine;
 
    @Autowired
    Car(Engine engine) {
        this.engine = engine;
    }
}

Setter 注入

class Car {
    private Engine engine;
    @Autowired
    void setEngine(Engine engine) {
        this.engine = engine;
    }
}

字段注入

class Car {
    @Autowired
    private Engine engine;
}

@Primary

当有多个相同类型的Bean时,使用@Primary来给一个Bean更高的优先权。

为什么需要@Primary?在某些情况下,我们需要注册超过一个相同类型的Bean。在这个例子中,我们有mySQLConnection()和oracleConnection()的Connection类型的bean。

@Configuration
public class Config {
    @Bean
    public Connection mySQLConnection() {
        return new MySQLConnection();
    } 
    @Bean
    public Connection oracleConnection() {
        return new OracleConnection();
    }
}

如果我们运行该应用程序,Spring会抛出NoUniqueBeanDefinitionException。为了访问具有相同类型的Bean,我们通常使用@Qualifier("beanName")注解,和@Autowired一起应用。在我们的案例中,我们在配置阶段配置Bean,所以@Qualifier不能在这里应用。关于@Qualifier会在本章后面讲到。

为了解决这个问题,Spring提供了@Primary注解。下面的例子展示了如何在一个Spring应用程序中使用@Primary注解。

@Primary注解可用于任何直接或间接用@Component注解的类或用@Bean注解的工厂方法。在这个例子中,我们将使用@Primary注解和@Component注解。

package com.demo.spring.primary;
public interface MessageService {
 public void sendMsg(); 
}
package com.demo.spring.primary;
import org.springframework.stereotype.Component;
@Component
public class FacebookMessageService implements MessageService {
    @Override
    public void sendMsg() {
        System.out.println("FacebookMessageService implementation here");
    }
}
package com.demo.spring.primary;
import org.springframework.stereotype.Component;
@Component
public class EmailMessageService implements MessageService {
    @Override
    public void sendMsg() {
        System.out.println("EmailMessageService Implementation here");
    }
}
package com.demo.spring.primary;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
@Primary
@Component
public class TwitterMessageService implements MessageService {
    @Override
    public void sendMsg() {
        System.out.println("TwitterMessageService Implementation here");
    }
}

请注意,在上述TwitterMessageService类中,我们添加了@Primary与@Component注解。

package com.demo.spring.primary;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.demo.spring.primary")
public class AppConfig {
 
}
public class Application {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        MessageService messageService = context.getBean(MessageService.class);
        messageService.sendMsg();
        context.close();
    }
}

Output:

TwitterMessageService Implementation here

@Qualifier

当我们创建了多个相同类型的Bean,但只想将其中一个与某个属性关联。可以使用@Qualifier注解和@Autowired注解来控制。

@Qualifier用于解决模糊的依赖关系,也就是说,它帮助@Autowired注解选择其中一个依赖关系。如果一个接口有多种实现,那么我们可以在运行时使用@Qualifier来选择所需的实现。

public interface MessageService {
    public void sendMsg(String message);
}
public class EmailService implements MessageService{
    public void sendMsg(String message) {
         System.out.println(message);
    }
}
public class TwitterService implements MessageService{
    public void sendMsg(String message) {
        System.out.println(message);
    }
}
public class SMSService implements MessageService{
    public void sendMsg(String message) {
         System.out.println(message);
    }
}
public interface MessageProcessor {
    public void processMsg(String message);
}
public class MessageProcessorImpl implements MessageProcessor {
    private MessageService messageService;
    // setter based DI
    @Autowired
    @Qualifier("TwitterService")
    public void setMessageService(MessageService messageService) {
        this.messageService = messageService;
    }
    // constructor based DI
    @Autowired
    public MessageProcessorImpl(@Qualifier("TwitterService") MessageService messageService) {
        this.messageService = messageService;
    }
    public void processMsg(String message) {
        messageService.sendMsg(message);
    }
}
@Configuration
@ComponentScan("com.demo.springframework.di")
public class AppConfiguration {
    @Bean(name="emailService")
    public MessageService emailService(){
         return new EmailService();
    }
    @Bean(name="twitterService")
    public MessageService twitterService(){
        return new TwitterService();
    }
    @Bean(name="smsService")
    public MessageService smsService(){
        return new SMSService();
    }
    @Bean
    public MessageProcessor messageProcessor(){
        return new MessageProcessorImpl(twitterService());
    }
}
public class TestApplication {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfiguration.class);
        MessageProcessor  userService = applicationContext.getBean(MessageProcessor.class);
        userService.processMsg("twitter message sending ");
    }
}

Output:

twitter message sending

@Resource

Spring支持通过@Resource(javax.annotation.Resource)方式注入,可以在字段或setter方法上加该注解,@Resource有一个name属性,如果不指定name,默认就是字段或setter方法名称。

public class SimpleMovieLister {
    private MovieFinder movieFinder;
    @Resource(name="myMovieFinder") 
    public void setMovieFinder(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }
}
public class SimpleMovieLister {
    private MovieFinder movieFinder;
    @Resource
    public void setMovieFinder(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }
}

@Value

该注解可用于向Spring管理的Bean中的字段注入值,它可以应用于字段或构造函数/方法参数级别。

我们需要一个属性文件来定义我们想用@Value注解注入的值。因此,我们首先需要在我们的配置类中定义一个@PropertySource--带有属性文件名。

value.from.file=Value got from the file
priority=high
listOfValues=A,B,C

注意:Spring Boot默认配置了一个PropertySourcesPlaceholderConfigurer的Bean,它将从application.properties和application.yml文件中获取属性。

@Value("${value.from.file}")
private String valueFromFile;

有时,我们需要注入一堆值。将它们定义为属性文件中单个属性用逗号分隔的值,或定义为系统属性并注入一个数组。例如listOfValues中定义了逗号分隔的值,所以数组的值将是["A","B", "C"]。

@Value("${listOfValues}")
private String[] valuesArray;

使用SpEL表达式

使用SpEL表达式获取配置文件中priority的值。

@Value("#{systemProperties['priority']}")
private String spelValue;

如果在property文件中没有定义属性,就会报nullvalue异常。为了防止这种情况,我们可以在SpEL表达式中提供一个默认值。如果属性没有定义,我们就为该字段设置默认值。

@Value("#{systemProperties['unknown'] ?: 'some default'}")
private String spelSomeDefault;

我们也可以用其它bean的属性值:

@Value("#{someBean.someValue}")
private Integer someBeanValue;

从属性配置中获取List列表:

@Value("#{'${listOfValues}'.split(',')}")
private List<String> valuesList;

把@Value注入到Map加入propeties文件中有如下key:

valuesMap={key1: '1', key2: '2', key3: '3'}

注意,Map中的值必须是单引号。

@Value("#{${valuesMap}}")
private Map<String, Integer> valuesMap;

如果要获取map中指定的key:

@Value("#{${valuesMap}.key1}")
private Integer valuesMapKey1;

如果不确定Map中是否包含key,我们可以使用一个安全的表达式,使其不会抛出异常,并且设置值为null:

@Value("#{${valuesMap}['unknownKey']}")
private Integer unknownMapKey;

为属性设置默认值:

@Value("#{${unknownMap : {key1: '1', key2: '2'}}}")
private Map<String, Integer> unknownMap;

@Value("#{${valuesMap}['unknownKey'] ?: 5}")
private Integer unknownMapKeyWithDefaultValue;

注入前过滤不需要的值:

@Value("#{${valuesMap}.?[value>'1']}")
private Map<String, Integer> valuesMapFiltered;

与构造函数一起注入

@Component
@PropertySource("classpath:application.properties")
public class PriorityProvider {

    private String priority;

    @Autowired
    public PriorityProvider(@Value("${priority:normal}") String priority) {
        this.priority = priority;
    }

    // standard getter
}

注意:默认配置文件是application.properties或application.yaml则不需要@PropertySource注解。

与Setter一起注入

@Component
@PropertySource("classpath:values.properties")
public class CollectionProvider {
    private List<String> values = new ArrayList<>();
    @Autowired
    public void setValues(@Value("#{'${listOfValues}'.split(',')}") List<String> values) {
        this.values.addAll(values);
    }
    // standard getter
}

@PostConstruct and @PreDestroy

我们可以自定义Bean的创建和销毁附动作。我们可以通过实现InitializingBean和DisposableBean接口来实现它。我们也可以用@PostConstruct和@PreDestroy注解来实现。

@PostConstruct

Spring只调用一次用@PostConstruct注释的方法,就在Bean属性初始化之后。请记住,即使没有任何东西需要初始化,这些方法也会运行。带有@PostConstruct注释的方法不能是静态的。

@Component
public class DbInit {
    @Autowired
    private UserRepository userRepository;
    @PostConstruct
    private void postConstruct() {
        User admin = new User("admin", "admin password");
        User normalUser = new User("user", "user password");
        userRepository.save(admin, normalUser);
    }
}

@PreDestroy

带有@PreDestroy注解的方法只运行一次,就在Spring将我们的Bean从容器中移除之前。带有@PreDestroy注解的方法不能是静态的。

@Component
public class UserRepository {
    private DbConnection dbConnection;
    @PreDestroy
    public void preDestroy() {
        dbConnection.close();
    }
}
spring框架学习 - spring IoC 之 基于注解的容器配置 接上一篇博客:https://blog.youkuaiyun.com/qq_43605444/article/details/121954378?spm=1001.2014.3001.5502 10、基于注解的容器配置 在配置 Spring 方面,注解是否比 XML 更好? 基于注解的配置的引入提出了这种方法是否比 XML“更好”的问题。 简短的回答是“视情况而定”。 长的答案是每种方法都有其优点和缺点,通常由开发人员决定哪种策略更适合他们。 由于它们的定义方式,注解在它们的声明中提供了很多上下文,从而导致更短和更 阅读详情

相关推荐

Spring注解容器配置指的是使用Spring框架的注解来配置和管理应用程序的组件和依赖关系

Component和@Autowired注解用于自动扫描和装配Bean,@Configuration和@Bean注解用于声明和注册Bean,@Qualifier注解用于指定要注入的具体Bean,@Value注解用于将值注入到属性中。在UserController类中,使用@Autowired注解和@Qualifier注解将名为"userService2"的Bean注入到userService字段中。Spring注解容器配置指的是使用Spring框架的注解来配置和管理应用程序的组件和依赖关系。

BbflNim的博客 65

Spring IoC容器:基于注解的容器配置

Spring IoC容器:基于注解的容器配置

听海边涛声 967

高效数据迁移:ICCAP到ADS的数据导入与导出实战指南

本文提供了从ICCAP到ADS进行高效、准确数据迁移的实战指南。针对射频与微波电路设计中的关键挑战,详细阐述了迁移前的战略规划、ICCAP数据的精细化导出(包括脚本化批处理)、ADS数据的多种导入方法(如Data Items、DML模型库及编程化API),并强调了数据完整性与准确性验证的重要性,确保模型参数和仿真结果在平台间可靠传递。

weixin_29291185的博客 132

Spring | 3.9 基于注解的容器配置

3.9 基于注解的容器配置 Spring框架中,注解是否优于XML配置? 基于注解的配置引入了这样一个问题:这种方法是否优于XML。简而言之,这要视情况而定。长话短说,每种方法都有其优缺点,通常由开发人员决定哪种策略更适合他们。由于它们的定义方式,注解在声明中提供了大量上下文,从而导致更短、更简洁的配置。然而,XML擅长在不接触组件源代码或重新编译它们的情况下连接组件。一些开发人员喜欢将连接靠近源...

星空下的程序猿 298

SPD5 集线器协议内容解析

​ 若不同SPD5 Hub后面的本地侧设备同时发送请求,则是22和23、24的混合过程,先通过LID裁决,再通过HID裁决,这里的LID是本地设备的,若LID一致,则看HID,由于SPD5 Hub的本地侧设备HID均为111,因此实际上是比较SPD5 Hub的HID,这个过程在前文提到,SPD5 Hub会转换HID。​ 若MR27[4]=1且MR27[3:0]=1,如果MR51[3:0]=1时,发送IBI,并且MR48[7]置1,将GETSTATUS CCC的待处理中断位[3:0]更新为0001。

weixin_50591344的博客 3860

RDMA性能调优实战:如何用ib_*命令榨干你的Mellanox网卡带宽?

本文深入探讨了如何利用ib_*命令工具集对RDMA网络进行深度性能调优,以充分释放Mellanox网卡的带宽潜力。文章从理解Send/Write/Read三种核心通信原语的差异入手,逐步指导读者通过调整消息大小、队列深度、内联数据等关键参数,并结合系统级的NUMA绑定、中断亲和性等优化策略,实现从基准测试到逼近硬件极限的性能提升。

weixin_29306011的博客 88

Java框架(三)--Spring IoC(4)--基于注解配置IoC容器

摆脱繁琐的XML形式的bean与依赖注入配置。 基于“声明式”的原则,更适合轻量级的现代企业应用。 让代码可读性变得更好,研发人员拥有更好的开发体验。组件类型注解 - 声明当前类的功能与职责。 自动装配注解 - 根据属性特征自动注入对象。 元数据注解 - 更细化的辅助IoC容器管理对象的注解。打开IDEA创建新的maven工程,在pom.xml引入Spring依赖 在resources目录下创建Spring配置文件applicationContext.xml 在com.ql.spring.ioc.dao包下

qq_32091929的博客 363

DSP28335做FFT傅里叶变换

1. 看了一下例程,居然没有FFT的例程,难道这个DSP28335不能做FFT吗?对了C2000系列是有C2000 ware这个库的。方便很多,不过目前不确定在C5000上运行的FFT能直接迁移到DSP28335上行不?测试了一下,是可以的,因为都是用的math.h,下面的一些正弦函数基本一样的 2. 硬件简介,其中DSP28335和TLV320AIC23B之间使用I2C接口进行寄存器配置,...

weixin_30390075的博客 3331

Spring5参考指南:基于注解的容器配置

文章目录@Required@Autowired@primary@Qualifier泛型@Resource@PostConstruct和@PreDestroy Spring的容器配置可以有两种方式,一种基于XML文件, 一种基于注解。注解注入在XML注入之前执行。因此,当两个同时使用时,XML配置会覆盖注解注入的属性。 本文会主要介绍 @Required,@Autowired, @PostConst...

程序那些事 3268

C#与欧姆龙PLC 通信——fins udp协议

该调试助手专门为了帮助大家学习以及测试Fins-Udp通信,下面进行详细介绍。

qq_34059233的博客 2874

华为OD机考双机位C卷 - 斗地主之顺子 (Java & Python& JS & C/C++ & GO )

华为OD机考双机位C卷 - 斗地主之顺子(OD上机考试双机位C卷)。提供在线OJ刷题。Java、C++、Python、GO语言、C语言、JavaScript题解,并提供完整思路讲解。

算法大师! 9693

Spring系列8:基于注解的Spring容器配置

前面几篇中我们说过,Spring容器支持3种方式进行bean定义信息的配置,现在具体说明下:前面的案例都是基于XML的,这篇介绍Annotation-based方式。该入门案例的bean的定义信息在xml文件这个,使用注解来进行依赖注入。@Autowired:将构造函数、字段、设置方法或配置方法标记为由 Spring 的依赖注入工具自动装配。定义类并通过@Autowird注入依赖 1.1、xml文件启用注解配置 1.2、获取容器中的bean进行使用 二、案例入门2 入门案例1中简化传统的xml配置依赖注

Joe192的博客 458

【MATLAB代码】TDOA+TOA融合算法,高精度定位。通过多边定位解算4个锚点、平面目标的位置,附代码

二维平面下的TOA、TDOA及混合定位算法,通过4个锚节点对目标点进行定位。

985工科博士毕业,专攻定位、导航和滤波等算法研究。从业10年,主要使用MATLAB 211

spring框架基于注解的容器配置

spring框架基于注解的容器配置  @Qualifier  @Autowired  @Resouce  @PostConstruct  @PreDestroy 注解这个东西真的很方便,我们使用起来也是特别的简单,和XML配合使用就是更是非常的舒服。就是具体的逻辑引用看起来不是特别的明显。但是使用注解已经是一个框架发展的趋势吧。大家都在往

码农崔的专栏 1134

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

五、Spring 框架,使用注解实现 Bean 容器的配置

五、Spring 注解开发

shiyu_951的博客 644

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

spring框架(五)基于注解配置的spring容器-源码解析

基于注解配置的spring容器-源码解析

qq_44818304的博客 936

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

Spring框架学习笔记(二):Spring IOC容器配置 Bean,分别基于XML配置bean 和 基于注解配置 bean

本文主要介绍spring框架中,基于xml配置文件配置bean和基于注解配置bean

2301_76144723的博客 1264

深入理解Spring4框架(八)——基于注解的容器配置

 基于注解的配置比XML更好吗?这得看情况,XML解耦了配置和原代码,而注解则精简了配置。     注解的注入会在XML之前,因此后者配置将会覆盖前者。可以将注解作为独立的Bean定义进行注册,也可以使用以下方式模糊注册。 <beans xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="ht

此博客已停用,博文会逐渐转移到新地址,http://blog.youkuaiyun.com/liupeifeng3514 1879

Java框架-Spring基于注解的IOC配置及纯注解

注解配置与xml配置都实现了减低程序间耦合的功能。 不同公司由不同习惯,有可能是纯xml、纯注解(很少)或者xml与注解混合使用(基于注解的IOC配置)。 1. 基于注解的IOC配置 1.1 创建一个简单案例 1.1.1 创建项目,添加依赖(pom.xml) &lt;!--导入spring组件包--&gt; &lt;dependency&gt; &lt;groupId&gt;org.s...

KeepStruggling的博客 528

Spring框架及Spring IoC核心容器介绍

SpringIoC核心容器介绍及其使用方式,推荐注解+配置类!!

weixin_44525733的博客 2514

Spring框架是如何初始化并注入Bean到容器中?

Spring框架对Bean的实例化并注入到Spring容器中,这个是框架的核心,简要记录一下,欢迎留言讨论... 正文如下: 主要有三种方式, 一,基于XML配置的注入, 这里就是过去我们常见的通过 application.xml 类配置各种bean,然后在web.xml中配置Spring监听器类ContextCleanupListener,监听读取 application.xml 文件内容,...

shenzhenNBA的专栏 2122

码农小汪-spring框架学习之6-spring基于注解的容器配置 @Qualifier @Autowired @Resouce @PostConstruct @PreDestroy

注解这个东西真的很方便,我们使用起来也是特别的简单,和XML配合使用就是更是非常的舒服。就是具体的逻辑引用看起来不是特别的明显。但是使用注解已经是一个框架发展的趋势吧。大家都在往这个方面上去靠。没得办法的!必须的学会。你说哈。如果以前的老的项目我们也是必须的懂XML,开发新的项目还是得学着去使用这些东西。注解比 XML 好么,简单的说得看情况。详细的说,各有优缺点。因为定义的方式,注解在声明处提供了

汪小哥 3239

Spring基于注解的配置详解

Spring配置 从Spring2.5开始支持基于注解的配置,使用@Configuration注解标注配置类,通过AnnotationConfigApplicationContext容器类读取注解配置信息。一个简单的例子如下,其中@Bean注解相当于配置文件中的<bean .../>。 基础类代码 public class Student { private Integer sId; private String sName; private String sGrad

qq_43408971的博客 320

Spring中bean注入初始化方式—通过注解@Configuration @bean

Spring的初始化bean的另一种方式——注解

vrenzhuv的专栏 3万+

Spring的IOC容器分析

Spring的IOC从入门到深入

caozhisanguo的专栏 4296
上一篇: 如何进阶 TypeScript 功底?一文带你理解 TS 中各种高级语法
下一篇: 手把手教你处理 JS 逆向之 CSS 偏移
JavaShark
博客等级 码龄4年 184粉丝 438原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值